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