]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
Kill needless #includes in source files
[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
29 namespace
30 {
31         ChanModeReference ban(NULL, "ban");
32         ChanModeReference inviteonlymode(NULL, "inviteonly");
33         ChanModeReference keymode(NULL, "key");
34         ChanModeReference limitmode(NULL, "limit");
35         ChanModeReference secretmode(NULL, "secret");
36         ChanModeReference privatemode(NULL, "private");
37         UserModeReference invisiblemode(NULL, "invisible");
38 }
39
40 Channel::Channel(const std::string &cname, time_t ts)
41         : name(cname), age(ts), topicset(0)
42 {
43         if (!ServerInstance->chanlist.insert(std::make_pair(cname, this)).second)
44                 throw CoreException("Cannot create duplicate channel " + cname);
45 }
46
47 void Channel::SetMode(ModeHandler* mh, bool on)
48 {
49         modes[mh->GetId()] = on;
50 }
51
52 void Channel::SetTopic(User* u, const std::string& ntopic)
53 {
54         this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
55         this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
56         this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
57         this->topicset = ServerInstance->Time();
58
59         FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
60 }
61
62 Membership* Channel::AddUser(User* user)
63 {
64         Membership*& memb = userlist[user];
65         if (memb)
66                 return NULL;
67
68         memb = new Membership(user, this);
69         return memb;
70 }
71
72 void Channel::DelUser(User* user)
73 {
74         UserMembIter it = userlist.find(user);
75         if (it != userlist.end())
76                 DelUser(it);
77 }
78
79 void Channel::CheckDestroy()
80 {
81         if (!userlist.empty())
82                 return;
83
84         ModResult res;
85         FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
86         if (res == MOD_RES_DENY)
87                 return;
88
89         chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
90         /* kill the record */
91         if (iter != ServerInstance->chanlist.end())
92         {
93                 FOREACH_MOD(OnChannelDelete, (this));
94                 ServerInstance->chanlist.erase(iter);
95         }
96
97         ClearInvites();
98         ServerInstance->GlobalCulls.AddItem(this);
99 }
100
101 void Channel::DelUser(const UserMembIter& membiter)
102 {
103         Membership* memb = membiter->second;
104         memb->cull();
105         delete memb;
106         userlist.erase(membiter);
107
108         // If this channel became empty then it should be removed
109         CheckDestroy();
110 }
111
112 Membership* Channel::GetUser(User* user)
113 {
114         UserMembIter i = userlist.find(user);
115         if (i == userlist.end())
116                 return NULL;
117         return i->second;
118 }
119
120 void Channel::SetDefaultModes()
121 {
122         ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
123                 ServerInstance->Config->DefaultModes.c_str());
124         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
125         std::string modeseq;
126         std::string parameter;
127
128         list.GetToken(modeseq);
129
130         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
131         {
132                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
133                 if (mode)
134                 {
135                         if (mode->IsPrefixMode())
136                                 continue;
137
138                         if (mode->GetNumParams(true))
139                                 list.GetToken(parameter);
140                         else
141                                 parameter.clear();
142
143                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
144                 }
145         }
146 }
147
148 /*
149  * add a channel to a user, creating the record for it if needed and linking
150  * it to the user record
151  */
152 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
153 {
154         if (user->registered != REG_ALL)
155         {
156                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
157                 return NULL;
158         }
159
160         /*
161          * We don't restrict the number of channels that remote users or users that are override-joining may be in.
162          * We restrict local users to <connect:maxchans> channels.
163          * We restrict local operators to <oper:maxchans> channels.
164          * This is a lot more logical than how it was formerly. -- w00t
165          */
166         if (!override)
167         {
168                 unsigned int maxchans = user->GetClass()->maxchans;
169                 if (user->IsOper())
170                 {
171                         unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
172                         // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
173                         if (!opermaxchans)
174                                 opermaxchans = ServerInstance->Config->OperMaxChans;
175                         if (opermaxchans)
176                                 maxchans = opermaxchans;
177                 }
178                 if (user->chans.size() >= maxchans)
179                 {
180                         user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s :You are on too many channels", cname.c_str());
181                         return NULL;
182                 }
183         }
184
185         // Crop channel name if it's too long
186         if (cname.length() > ServerInstance->Config->Limits.ChanMax)
187                 cname.resize(ServerInstance->Config->Limits.ChanMax);
188
189         Channel* chan = ServerInstance->FindChan(cname);
190         bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
191         std::string privs; // Prefix mode(letter)s to give to the joining user
192
193         if (!chan)
194         {
195                 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
196
197                 if (override == false)
198                 {
199                         // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
200                         ModResult MOD_RESULT;
201                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
202                         if (MOD_RESULT == MOD_RES_DENY)
203                                 return NULL; // A module wasn't happy with the join, abort
204                 }
205
206                 chan = new Channel(cname, ServerInstance->Time());
207                 // Set the default modes on the channel (<options:defaultmodes>)
208                 chan->SetDefaultModes();
209         }
210         else
211         {
212                 /* Already on the channel */
213                 if (chan->HasUser(user))
214                         return NULL;
215
216                 if (override == false)
217                 {
218                         ModResult MOD_RESULT;
219                         FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
220
221                         // A module explicitly denied the join and (hopefully) generated a message
222                         // describing the situation, so we may stop here without sending anything
223                         if (MOD_RESULT == MOD_RES_DENY)
224                                 return NULL;
225
226                         // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
227                         // most of the time) then proceed to check channel modes +k, +i, +l and bans,
228                         // in this order.
229                         // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
230                         // then this entire section is skipped
231                         if (MOD_RESULT == MOD_RES_PASSTHRU)
232                         {
233                                 std::string ckey = chan->GetModeParameter(keymode);
234                                 bool invited = user->IsInvited(chan);
235                                 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
236
237                                 if (!ckey.empty())
238                                 {
239                                         FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
240                                         if (!MOD_RESULT.check((ckey == key) || can_bypass))
241                                         {
242                                                 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
243                                                 user->WriteNumeric(ERR_BADCHANNELKEY, "%s :Cannot join channel (Incorrect channel key)", chan->name.c_str());
244                                                 return NULL;
245                                         }
246                                 }
247
248                                 if (chan->IsModeSet(inviteonlymode))
249                                 {
250                                         FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
251                                         if (!MOD_RESULT.check(invited))
252                                         {
253                                                 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s :Cannot join channel (Invite only)", chan->name.c_str());
254                                                 return NULL;
255                                         }
256                                 }
257
258                                 std::string limit = chan->GetModeParameter(limitmode);
259                                 if (!limit.empty())
260                                 {
261                                         FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
262                                         if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
263                                         {
264                                                 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
265                                                 return NULL;
266                                         }
267                                 }
268
269                                 if (chan->IsBanned(user) && !can_bypass)
270                                 {
271                                         user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
272                                         return NULL;
273                                 }
274
275                                 /*
276                                  * If the user has invites for this channel, remove them now
277                                  * after a successful join so they don't build up.
278                                  */
279                                 if (invited)
280                                 {
281                                         user->RemoveInvite(chan);
282                                 }
283                         }
284                 }
285         }
286
287         // We figured that this join is allowed and also created the
288         // channel if it didn't exist before, now do the actual join
289         chan->ForceJoin(user, &privs, false, created_by_local);
290         return chan;
291 }
292
293 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
294 {
295         if (IS_SERVER(user))
296         {
297                 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
298                 return NULL;
299         }
300
301         Membership* memb = this->AddUser(user);
302         if (!memb)
303                 return NULL; // Already on the channel
304
305         user->chans.push_front(memb);
306
307         if (privs)
308         {
309                 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
310                 // remote user and his own server set the modes), then set them internally now
311                 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
312                 {
313                         PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
314                         if (mh)
315                         {
316                                 std::string nick = user->nick;
317                                 // Set the mode on the user
318                                 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
319                         }
320                 }
321         }
322
323         // 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
324         CUList except_list;
325         FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
326
327         this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
328
329         /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
330         if ((GetUserCounter() > 1) && (!memb->modes.empty()))
331         {
332                 std::string ms = memb->modes;
333                 for(unsigned int i=0; i < memb->modes.length(); i++)
334                         ms.append(" ").append(user->nick);
335
336                 except_list.insert(user);
337                 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
338         }
339
340         if (IS_LOCAL(user))
341         {
342                 if (this->topicset)
343                 {
344                         user->WriteNumeric(RPL_TOPIC, "%s :%s", this->name.c_str(), this->topic.c_str());
345                         user->WriteNumeric(RPL_TOPICTIME, "%s %s %lu", this->name.c_str(), this->setby.c_str(), (unsigned long)this->topicset);
346                 }
347                 this->UserList(user);
348         }
349
350         FOREACH_MOD(OnPostJoin, (memb));
351         return memb;
352 }
353
354 bool Channel::IsBanned(User* user)
355 {
356         ModResult result;
357         FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
358
359         if (result != MOD_RES_PASSTHRU)
360                 return (result == MOD_RES_DENY);
361
362         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
363         const ListModeBase::ModeList* bans = banlm->GetList(this);
364         if (bans)
365         {
366                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
367                 {
368                         if (CheckBan(user, it->mask))
369                                 return true;
370                 }
371         }
372         return false;
373 }
374
375 bool Channel::CheckBan(User* user, const std::string& mask)
376 {
377         ModResult result;
378         FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
379         if (result != MOD_RES_PASSTHRU)
380                 return (result == MOD_RES_DENY);
381
382         // extbans were handled above, if this is one it obviously didn't match
383         if ((mask.length() <= 2) || (mask[1] == ':'))
384                 return false;
385
386         std::string::size_type at = mask.find('@');
387         if (at == std::string::npos)
388                 return false;
389
390         const std::string nickIdent = user->nick + "!" + user->ident;
391         std::string prefix = mask.substr(0, at);
392         if (InspIRCd::Match(nickIdent, prefix, NULL))
393         {
394                 std::string suffix = mask.substr(at + 1);
395                 if (InspIRCd::Match(user->host, suffix, NULL) ||
396                         InspIRCd::Match(user->dhost, suffix, NULL) ||
397                         InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
398                         return true;
399         }
400         return false;
401 }
402
403 ModResult Channel::GetExtBanStatus(User *user, char type)
404 {
405         ModResult rv;
406         FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
407         if (rv != MOD_RES_PASSTHRU)
408                 return rv;
409
410         ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
411         const ListModeBase::ModeList* bans = banlm->GetList(this);
412         if (bans)
413         {
414                 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
415                 {
416                         if (CheckBan(user, it->mask))
417                                 return MOD_RES_DENY;
418                 }
419         }
420         return MOD_RES_PASSTHRU;
421 }
422
423 /* Channel::PartUser
424  * Remove a channel from a users record, remove the reference to the Membership object
425  * from the channel and destroy it.
426  */
427 void Channel::PartUser(User *user, std::string &reason)
428 {
429         UserMembIter membiter = userlist.find(user);
430
431         if (membiter != userlist.end())
432         {
433                 Membership* memb = membiter->second;
434                 CUList except_list;
435                 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
436
437                 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
438
439                 // Remove this channel from the user's chanlist
440                 user->chans.erase(memb);
441                 // Remove the Membership from this channel's userlist and destroy it
442                 this->DelUser(membiter);
443         }
444 }
445
446 void Channel::KickUser(User* src, const UserMembIter& victimiter, const std::string& reason)
447 {
448         Membership* memb = victimiter->second;
449         CUList except_list;
450         FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
451
452         User* victim = memb->user;
453         WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
454
455         victim->chans.erase(memb);
456         this->DelUser(victimiter);
457 }
458
459 void Channel::WriteChannel(User* user, const char* text, ...)
460 {
461         std::string textbuffer;
462         VAFORMAT(textbuffer, text, text);
463         this->WriteChannel(user, textbuffer);
464 }
465
466 void Channel::WriteChannel(User* user, const std::string &text)
467 {
468         const std::string message = ":" + user->GetFullHost() + " " + text;
469
470         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
471         {
472                 if (IS_LOCAL(i->first))
473                         i->first->Write(message);
474         }
475 }
476
477 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
478 {
479         std::string textbuffer;
480         VAFORMAT(textbuffer, text, text);
481         this->WriteChannelWithServ(ServName, textbuffer);
482 }
483
484 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
485 {
486         const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
487
488         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
489         {
490                 if (IS_LOCAL(i->first))
491                         i->first->Write(message);
492         }
493 }
494
495 /* write formatted text from a source user to all users on a channel except
496  * for the sender (for privmsg etc) */
497 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
498 {
499         std::string textbuffer;
500         VAFORMAT(textbuffer, text, text);
501         this->WriteAllExceptSender(user, serversource, status, textbuffer);
502 }
503
504 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
505 {
506         std::string textbuffer;
507         VAFORMAT(textbuffer, text, text);
508         textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
509         this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
510 }
511
512 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
513 {
514         const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
515         this->RawWriteAllExcept(user, serversource, status, except_list, message);
516 }
517
518 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
519 {
520         unsigned int minrank = 0;
521         if (status)
522         {
523                 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
524                 if (mh)
525                         minrank = mh->GetPrefixRank();
526         }
527         for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
528         {
529                 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
530                 {
531                         /* User doesn't have the status we're after */
532                         if (minrank && i->second->getRank() < minrank)
533                                 continue;
534
535                         i->first->Write(out);
536                 }
537         }
538 }
539
540 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
541 {
542         CUList except_list;
543         except_list.insert(user);
544         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
545 }
546
547 const char* Channel::ChanModes(bool showkey)
548 {
549         static std::string scratch;
550         std::string sparam;
551
552         scratch.clear();
553
554         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
555         for(int n = 0; n < 64; n++)
556         {
557                 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
558                 if (mh && IsModeSet(mh))
559                 {
560                         scratch.push_back(n + 65);
561
562                         ParamModeBase* pm = mh->IsParameterMode();
563                         if (!pm)
564                                 continue;
565
566                         if (n == 'k' - 65 && !showkey)
567                         {
568                                 sparam += " <key>";
569                         }
570                         else
571                         {
572                                 sparam += ' ';
573                                 pm->GetParameter(this, sparam);
574                         }
575                 }
576         }
577
578         scratch += sparam;
579         return scratch.c_str();
580 }
581
582 /* compile a userlist of a channel into a string, each nick seperated by
583  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
584  */
585 void Channel::UserList(User* user, bool has_user)
586 {
587         bool has_privs = user->HasPrivPermission("channels/auspex");
588         std::string list;
589         list.push_back(this->IsModeSet(secretmode) ? '@' : this->IsModeSet(privatemode) ? '*' : '=');
590         list.push_back(' ');
591         list.append(this->name).append(" :");
592         std::string::size_type pos = list.size();
593
594         const size_t maxlen = ServerInstance->Config->Limits.MaxLine - 10 - ServerInstance->Config->ServerName.size();
595         std::string prefixlist;
596         std::string nick;
597         for (UserMembIter i = userlist.begin(); i != userlist.end(); ++i)
598         {
599                 if ((!has_user) && (i->first->IsModeSet(invisiblemode)) && (!has_privs))
600                 {
601                         /*
602                          * user is +i, and source not on the channel, does not show
603                          * nick in NAMES list
604                          */
605                         continue;
606                 }
607
608                 Membership* memb = i->second;
609
610                 prefixlist.clear();
611                 char prefix = memb->GetPrefixChar();
612                 if (prefix)
613                         prefixlist.push_back(prefix);
614                 nick = i->first->nick;
615
616                 ModResult res;
617                 FIRST_MOD_RESULT(OnNamesListItem, res, (user, memb, prefixlist, nick));
618
619                 // See if a module wants us to exclude this user from NAMES
620                 if (res == MOD_RES_DENY)
621                         continue;
622
623                 if (list.size() + prefixlist.length() + nick.length() + 1 > maxlen)
624                 {
625                         /* list overflowed into multiple numerics */
626                         user->WriteNumeric(RPL_NAMREPLY, list);
627
628                         // Erase all nicks, keep the constant part
629                         list.erase(pos);
630                 }
631
632                 list.append(prefixlist).append(nick).push_back(' ');
633         }
634
635         // Only send the user list numeric if there is at least one user in it
636         if (list.size() != pos)
637                 user->WriteNumeric(RPL_NAMREPLY, list);
638
639         user->WriteNumeric(RPL_ENDOFNAMES, "%s :End of /NAMES list.", this->name.c_str());
640 }
641
642 /* returns the status character for a given user on a channel, e.g. @ for op,
643  * % for halfop etc. If the user has several modes set, the highest mode
644  * the user has must be returned.
645  */
646 char Membership::GetPrefixChar() const
647 {
648         char pf = 0;
649         unsigned int bestrank = 0;
650
651         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
652         {
653                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
654                 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
655                 {
656                         bestrank = mh->GetPrefixRank();
657                         pf = mh->GetPrefix();
658                 }
659         }
660         return pf;
661 }
662
663 unsigned int Membership::getRank()
664 {
665         char mchar = modes.c_str()[0];
666         unsigned int rv = 0;
667         if (mchar)
668         {
669                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
670                 if (mh)
671                         rv = mh->GetPrefixRank();
672         }
673         return rv;
674 }
675
676 const char* Membership::GetAllPrefixChars() const
677 {
678         static char prefix[64];
679         int ctr = 0;
680
681         for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
682         {
683                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
684                 if (mh && mh->GetPrefix())
685                         prefix[ctr++] = mh->GetPrefix();
686         }
687         prefix[ctr] = 0;
688
689         return prefix;
690 }
691
692 unsigned int Channel::GetPrefixValue(User* user)
693 {
694         UserMembIter m = userlist.find(user);
695         if (m == userlist.end())
696                 return 0;
697         return m->second->getRank();
698 }
699
700 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
701 {
702         char prefix = delta_mh->GetModeChar();
703         for (unsigned int i = 0; i < modes.length(); i++)
704         {
705                 char mchar = modes[i];
706                 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
707                 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
708                 {
709                         modes = modes.substr(0,i) +
710                                 (adding ? std::string(1, prefix) : "") +
711                                 modes.substr(mchar == prefix ? i+1 : i);
712                         return adding != (mchar == prefix);
713                 }
714         }
715         if (adding)
716                 modes.push_back(prefix);
717         return adding;
718 }
719
720 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
721 {
722         if ((timeout != 0) && (ServerInstance->Time() >= timeout))
723                 // Expired, don't bother
724                 return;
725
726         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
727
728         Invitation* inv = Invitation::Find(c, u, false);
729         if (inv)
730         {
731                  if ((inv->expiry == 0) || (inv->expiry > timeout))
732                         return;
733                 inv->expiry = timeout;
734                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
735         }
736         else
737         {
738                 inv = new Invitation(c, u, timeout);
739                 c->invites.push_front(inv);
740                 u->invites.push_front(inv);
741                 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
742         }
743 }
744
745 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
746 {
747         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);
748
749         Invitation* result = NULL;
750         for (InviteList::iterator i = u->invites.begin(); i != u->invites.end(); )
751         {
752                 Invitation* inv = *i;
753                 ++i;
754
755                 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
756                 {
757                         /* Expired invite, remove it. */
758                         std::string expiration = InspIRCd::TimeString(inv->expiry);
759                         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
760                         delete inv;
761                 }
762                 else
763                 {
764                         /* Is it what we're searching for? */
765                         if (inv->chan == c)
766                         {
767                                 result = inv;
768                                 break;
769                         }
770                 }
771         }
772
773         ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
774         return result;
775 }
776
777 Invitation::~Invitation()
778 {
779         // Remove this entry from both lists
780         chan->invites.erase(this);
781         user->invites.erase(this);
782         ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "Invitation::~ %p", (void*) this);
783 }