コード例 #1
0
ファイル: CKickBan.cpp プロジェクト: fizyk20/ircbot
void CKickBan::endVote()
{
	if(vote == NULL) return;

	if(vote -> numVotes() < settings -> GetInt("vote_min_votes"))
		core -> sendMsgChannel("Zbyt niska frekwencja.");
	else
	{
		if(vote -> resultFor() < settings -> GetDouble("vote_pass_min"))
			core -> sendMsgChannel("Wynik głosowania: przeciw.");
		else
		{
			core -> sendMsgChannel("Wynik głosowania: za.");

			switch(voteType)
			{
			case Kick:
				core -> kickUser(voteTarget, "Lud przemówił.");
				break;
			case Ban:
				ban(voteTarget, voteMask);
				core -> kickUser(voteTarget, "Lud przemówił.");
				break;
			case Unban:
				unban(voteTarget);
				break;
			}
		}
	}

	state = Waiting;
	delete vote;
	vote = NULL;
}
コード例 #2
0
ファイル: netburst.cpp プロジェクト: bandicot/inspircd
/** Send one or more FJOINs for a channel of users.
 * If the length of a single line is more than 480-NICKMAX
 * in length, it is split over multiple lines.
 * Send one or more FMODEs for a channel with the
 * channel bans, if there's any.
 */
void TreeSocket::SendFJoins(Channel* c)
{
	std::string line(":");
	line.append(ServerInstance->Config->GetSID()).append(" FJOIN ").append(c->name).append(1, ' ').append(ConvToStr(c->age)).append(" +");
	std::string::size_type erase_from = line.length();
	line.append(c->ChanModes(true)).append(" :");

	const UserMembList *ulist = c->GetUsers();

	for (UserMembCIter i = ulist->begin(); i != ulist->end(); ++i)
	{
		const std::string& modestr = i->second->modes;
		if ((line.length() + modestr.length() + UIDGenerator::UUID_LENGTH + 2) > 480)
		{
			this->WriteLine(line);
			line.erase(erase_from);
			line.append(" :");
		}
		line.append(modestr).append(1, ',').append(i->first->uuid).push_back(' ');
	}
	this->WriteLine(line);

	ModeReference ban(NULL, "ban");
	static_cast<ListModeBase*>(*ban)->DoSyncChannel(c, Utils->Creator, this);
}
コード例 #3
0
ファイル: cmd.c プロジェクト: CrypticSwarm/APE_Server
unsigned int cmd_ban(callbackp *callbacki)
{
	CHANNEL *chan;
	RAW *newraw;
	json *jlist;
	
	USERS *victim;

	if ((chan = getchan(callbacki->param[2], callbacki->g_ape)) == NULL) {
		send_error(callbacki->call_user, "UNKNOWN_CHANNEL", "103", callbacki->g_ape);
		
	
	} else if (!isonchannel(callbacki->call_user, chan)) {

		send_error(callbacki->call_user, "NOT_IN_CHANNEL", "104", callbacki->g_ape);
	
	} else if (getuchan(callbacki->call_user, chan)->level < 3) {

		
		send_error(callbacki->call_user, "CANT_BAN", "107", callbacki->g_ape);
		
	} else {
		victim = seek_user(callbacki->param[3], chan->name, callbacki->g_ape);
		
		if (victim == NULL) {

			send_error(callbacki->call_user, "UNKNOWN_USER", "102", callbacki->g_ape);
			
		} else if (victim->flags & FLG_NOKICK) {
			send_error(callbacki->call_user, "USER_PROTECTED", "106", callbacki->g_ape);
			
			// Bad boy :-)
			jlist = NULL;
			set_json("banner", NULL, &jlist);
			json_attach(jlist, get_json_object_user(callbacki->call_user), JSON_OBJECT);
			
			set_json("channel", NULL, &jlist);
			json_attach(jlist, get_json_object_channel(chan), JSON_OBJECT);
						
			newraw = forge_raw("TRY_BAN", jlist);
			
			post_raw(newraw, victim, callbacki->g_ape);
			
		} else if (strlen(callbacki->param[4]) > 255 || atoi(callbacki->param[5]) > 44640) { // 31 days max

			send_error(callbacki->call_user, "REASON_OR_TIME_TOO_LONG", "107", callbacki->g_ape);
		} else {
			ban(chan, callbacki->call_user, victim->ip, callbacki->param[4], atoi(callbacki->param[5]), callbacki->g_ape);
		}
		
	}
	
	return (FOR_NOTHING);
}
コード例 #4
0
ファイル: botserv.cpp プロジェクト: SaberUK/anope
	void OnJoinChannel(User *user, Channel *c) override
	{
		if (!Config || !IRCD)
			return;

		ServiceBot *bi = user->server == Me ? dynamic_cast<ServiceBot *>(user) : NULL;
		if (bi && Config->GetModule(this)->Get<bool>("smartjoin"))
		{
			std::vector<Anope::string> bans = c->GetModeList("BAN");

			/* We check for bans */
			for (unsigned int i = 0; i < bans.size(); ++i)
			{
				Entry ban("BAN", bans[i]);
				if (ban.Matches(user))
					c->RemoveMode(NULL, "BAN", ban.GetMask());
			}

			Anope::string Limit;
			unsigned limit = 0;
			try
			{
				if (c->GetParam("LIMIT", Limit))
					limit = convertTo<unsigned>(Limit);
			}
			catch (const ConvertException &) { }

			/* Should we be invited? */
			if (c->HasMode("INVITE") || (limit && c->users.size() >= limit))
			{
				ChannelMode *cm = ModeManager::FindChannelModeByName("OP");
				char symbol = cm ? anope_dynamic_static_cast<ChannelModeStatus *>(cm)->symbol : 0;
				IRCD->SendNotice(bi, (symbol ? Anope::string(symbol) : "") + c->name, "%s invited %s into the channel.", user->nick.c_str(), user->nick.c_str());
			}

			ModeManager::ProcessModes();
		}

		if (user->server != Me && c->ci && c->ci->GetBot())
		{
			/**
			 * We let the bot join even if it was an ignored user, as if we don't,
			 * and the ignored user doesn't just leave, the bot will never
			 * make it into the channel, leaving the channel botless even for
			 * legit users - Rob
			 **/
			/* This is before the user has joined the channel, so check usercount + 1 */
			if (c->users.size() + 1 >= Config->GetModule(this)->Get<unsigned>("minusers") && !c->FindUser(c->ci->GetBot()))
			{
				ChannelStatus status(Config->GetModule(this)->Get<Anope::string>("botmodes"));
				c->ci->GetBot()->Join(c, &status);
			}
		}
	}
コード例 #5
0
ファイル: botserv.cpp プロジェクト: SaberUK/anope
	EventReturn OnChannelModeSet(Channel *c, const MessageSource &source, ChannelMode *mode, const Anope::string &param) override
	{
		if (source.GetUser() && !source.GetBot() && Config->GetModule(this)->Get<bool>("smartjoin") && mode->name == "BAN" && c->ci && c->ci->GetBot() && c->FindUser(c->ci->GetBot()))
		{
			ServiceBot *bi = c->ci->GetBot();

			Entry ban("BAN", param);
			if (ban.Matches(bi))
				c->RemoveMode(bi, "BAN", param);
		}

		return EVENT_CONTINUE;
	}
コード例 #6
0
 string mostCommonWord(string paragraph, vector<string>& banned) {
     unordered_set<string> ban(banned.begin(), banned.end());
     unordered_map<string, int> count;
     for (auto & c: paragraph) {
         c = isalpha(c) ? tolower(c) : ' ';
     }
     istringstream iss(paragraph);
     string w, res = "";
     int mx_cnt = 0;
     while (iss >> w) {
         if (ban.find(w) == ban.end() && ++count[w] > mx_cnt) {
             res = w;
             mx_cnt = count[w];
         }
     }
     return res;
 }
コード例 #7
0
ファイル: SceneNet.cpp プロジェクト: Daivuk/BaboViolent2
void Scene::ban(CString playerName)
{
	if (server)
	{
		for (int i=0;i<MAX_PLAYER;++i)
		{
			if (server->game)
				if (server->game->players[i])
			{
				if (textColorLess(server->game->players[i]->name) == textColorLess(playerName))
				{
					ban(server->game->players[i]->playerID);
				}
			}
		}
	}
}
コード例 #8
0
void ConfigReaderThread::Finish()
{
	ServerConfig* old = ServerInstance->Config;
	ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Switching to new configuration...");
	ServerInstance->Config = this->Config;
	Config->Apply(old, TheUserUID);

	if (Config->valid)
	{
		/*
		 * Apply the changed configuration from the rehash.
		 *
		 * XXX: The order of these is IMPORTANT, do not reorder them without testing
		 * thoroughly!!!
		 */
		ServerInstance->XLines->CheckELines();
		ServerInstance->XLines->ApplyLines();
		ChanModeReference ban(NULL, "ban");
		static_cast<ListModeBase*>(*ban)->DoRehash();
		Config->ApplyDisabledCommands(Config->DisabledCommands);
		User* user = ServerInstance->FindNick(TheUserUID);

		ConfigStatus status(user);
		const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
		for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
			i->second->ReadConfig(status);

		// The description of this server may have changed - update it for WHOIS etc.
		ServerInstance->FakeClient->server->description = Config->ServerDesc;

		ServerInstance->ISupport.Build();

		ServerInstance->Logs->CloseLogs();
		ServerInstance->Logs->OpenFileLogs();

		if (Config->RawLog && !old->RawLog)
			ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");

		Config = old;
	}
	else
	{
		// whoops, abort!
		ServerInstance->Config = old;
	}
}
コード例 #9
0
void AntiDos::addKick(const QString &ip)
{
    QList<time_t> &l = kicksPerIp[ip];

    int i = 0;

    /* Removing kicks older than 15 minutes */
    while (i < l.size()) {
        if (time(NULL)-l[i] > 900) {
            i++;
        }  else {
            break;
        }
    }

    l.erase(l.begin(), l.begin()+i);

    if (l.size() >= ban_after_x_kicks) {
        emit ban(ip);
    }
}
コード例 #10
0
ファイル: configreader.cpp プロジェクト: bandicot/inspircd
void ConfigReaderThread::Finish()
{
	ServerConfig* old = ServerInstance->Config;
	ServerInstance->Logs->Log("CONFIG",LOG_DEBUG,"Switching to new configuration...");
	ServerInstance->Config = this->Config;
	Config->Apply(old, TheUserUID);

	if (Config->valid)
	{
		/*
		 * Apply the changed configuration from the rehash.
		 *
		 * XXX: The order of these is IMPORTANT, do not reorder them without testing
		 * thoroughly!!!
		 */
		ServerInstance->XLines->CheckELines();
		ServerInstance->XLines->ApplyLines();
		ModeReference ban(NULL, "ban");
		static_cast<ListModeBase*>(*ban)->DoRehash();
		Config->ApplyDisabledCommands(Config->DisabledCommands);
		User* user = ServerInstance->FindNick(TheUserUID);
		FOREACH_MOD(I_OnRehash, OnRehash(user));
		ServerInstance->ISupport.Build();

		ServerInstance->Logs->CloseLogs();
		ServerInstance->Logs->OpenFileLogs();

		if (Config->RawLog && !old->RawLog)
			ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");

		Config = old;
	}
	else
	{
		// whoops, abort!
		ServerInstance->Config = old;
	}
}
コード例 #11
0
    string mostCommonWord(string paragraph, vector<string>& banned) {
      //initialize set to contain banned word, lookup is faster in set compared to vector
      unordered_set<string> ban(banned.begin(),banned.end());
      //remove all punctuations from the string
      for (auto &c : paragraph) {
        if (!isalpha(c)) {
          c = ' ';
        } else {
          c = tolower(c);
        }
      }
      //extract the words from the paragraph
      unordered_map<string,int> m; //map to store count of each non banned word
      istringstream ss;
      ss.str(paragraph);
      string w;
      while(ss>>w) {
        if (ban.find(w) == ban.end()) {
          //if in map increase the count else add in map with count 1
          if (m.find(w) != m.end()) {
            m[w] += 1;
          } else {
            m[w] = 1;
          }
        }
        //cout<<w<<"\n";
      }
      int max_count = 0;
      for (auto it = m.begin(); it != m.end(); ++it) {
        if (it->second > max_count) {
          max_count = it->second;
          res = it->first;
        }
      }
      return res;

    }
コード例 #12
0
PlayersWindow::PlayersWindow(QWidget *parent, int expireDays)
    : QWidget (parent)
{
    setAttribute(Qt::WA_DeleteOnClose, true);
    resize(726, this->height());

    QGridLayout *mylayout = new QGridLayout(this);

    const auto &members = SecurityManager::getMembers();

    mytable = new QCompactTable(members.size(),7);

    mytable->setShowGrid(true);
    mylayout->addWidget(mytable,0,0,1,6);

    QMap<int, QString> authgrade;
    authgrade[0] = "User";
    authgrade[1] = "Mod";
    authgrade[2] = "Admin";
    authgrade[3] = "Owner";

    QStringList headers;
    headers << "Player" << "Authority" << "Banned Status" << "Registered" << "IP" << "Last Appearance" << "Expires In";
    mytable->setHorizontalHeaderLabels(headers);

    int i = 0;

    for (auto it = members.begin(); it != members.end(); ++it) {
        const SecurityManager::Member &m = it->second;

        QTableWidgetItem *witem = new QTableWidgetItem(m.name);
        mytable->setItem(i, 0, witem);

        witem = new QTableWidgetItem(authgrade[m.authority()]);
        mytable->setItem(i, 1, witem);

        QString bannedString = "Banned";
        int expiration = m.ban_expire_time - QDateTime::currentDateTimeUtc().toTime_t();
        if(expiration < 0) {
            if (m.ban_expire_time != 0)
            bannedString = "Expires on Login";
        } else {
            if(expiration < 60) {
                if(expiration == 1) {
                    bannedString.append(QString(" (%1 second)").arg(expiration));
                } else {
                    bannedString.append(QString(" (%2 seconds)").arg(expiration));
                }
            } else {
                if(expiration >= 60) {
                    expiration = expiration / 60;
                    if(expiration == 1) {
                        bannedString.append(QString(" (%1 minute)").arg(expiration));
                    } else {
                        bannedString.append(QString(" (%2 minutes)").arg(expiration));
                    }
                }
            }
        }
        witem = new QTableWidgetItem(m.banned ? bannedString : "Fine");
        mytable->setItem(i, 2, witem);

        witem = new QTableWidgetItem(m.isProtected() > 0 ? "Yes" : "No");
        mytable->setItem(i, 3, witem);

        witem = new QTableWidgetItem(m.ip);
        mytable->setItem(i, 4, witem);

        witem = new QTableWidgetItem(m.date);
        mytable->setItem(i, 5, witem);

        witem = new QTableWidgetItem(QString::number(expireDays - QDate::fromString(m.date, Qt::ISODate).daysTo(QDate::currentDate())) + " Days");
        mytable->setItem(i, 6, witem);

        i++;
    }

    //mytable->sortByColumn(0, Qt::AscendingOrder);

    //mytable->setSortingEnabled(true);

    QPushButton *_authority = new QPushButton(tr("&Authority"));
    QMenu *m = new QMenu(_authority);
    m->addAction(tr("User"), this, SLOT(user()));
    m->addAction(tr("Moderator"), this, SLOT(mod()));
    m->addAction(tr("Administrator"), this, SLOT(admin()));
    m->addAction(tr("Owner"), this, SLOT(owner()));
    _authority->setMenu(m);

    QPushButton *_ban = new QPushButton(tr("&Ban"));
    QPushButton *_unban = new QPushButton(tr("U&nban"));
    QPushButton *_clpass = new QPushButton(tr("&Clear Password"));
    QCheckBox *enableSorting = new QCheckBox(tr("&Enable sorting"));

    mylayout->addWidget(_authority,1,0);
    mylayout->addWidget(_ban,1,2);
    mylayout->addWidget(_unban,1,3);
    mylayout->addWidget(_clpass,1,4);
    mylayout->addWidget(enableSorting, 1, 5);

    if (mytable->rowCount() == 0)
        return;

    connect(_ban,SIGNAL(clicked()),SLOT(ban()));
    connect(_unban,SIGNAL(clicked()),SLOT(unban()));
    connect(_clpass,SIGNAL(clicked()),SLOT(clpass()));
    connect(enableSorting, SIGNAL(toggled(bool)), SLOT(enableSorting(bool)));
}
コード例 #13
0
ファイル: areal.cpp プロジェクト: finalist736/gamechatserver
void Areal::dispatch(QList<QByteArray> list, AbsConnection *who)
{
    removeFromBanlist();
    if (list.length() == 0)
    {
        return;
    }
    QByteArray cmd = list.at(0);

    if (cmd == "CC")
    {
        if (list.length() == 2)
        {
            bool exists = false;
            QByteArray name = list.at(1);
            QHash<quint32, Channel*>::iterator it;
            for (it=m_channels.begin();it!=m_channels.end();++it)
            {
                if (name == it.value()->name())
                {
                    exists = true;
                    it.value()->add(who);
                    who->send(QVariantList() << "CC" << name << it.value()->id());
                    break;
                }
            }
            if (!exists)
            {
                ++m_next_channel;
                Channel * channel = m_channels[m_next_channel] = new Channel(m_next_channel, name, this);
                channel->add(who);
                who->send(QVariantList() << "CC" << name << channel->id());
            }
        }
    }
    else if (cmd == "LC")
    {
        if (list.length() == 2)
        {
            QByteArray name = list.at(1);
            QHash<quint32, Channel*>::iterator it;
            for (it=m_channels.begin();it!=m_channels.end();++it)
            {
                Channel * channel = it.value();
                if (name == channel->name())
                {
                    channel->remove(who);
                    if (channel->isEmpty())
                    {
                        channel->deleteLater();
                        m_channels.remove(it.key());
                    }
                    who->send(QVariantList() << "LC" << "OK");
                    break;
                }
            }
        }
    }
    else if (cmd == "SM")
    {
        if (list.length() == 3)
        {
            quint32 id = list.at(1).toInt();
            if (m_channels.contains(id))
            {
                QByteArray text = list.at(2);
                Channel * channel = m_channels.value(id);

                if (text.left(1) == "/")
                {
                    if (text.left(4) == "/ban")
                    {
                        ban(text, who);
                    }
                    else if (text.left(6) == "/unban")
                    {
                        unban(text, who);
                    }
                    else
                    {
                        m_cmd.dispatch(text, who, channel);
                    }
                }
                else
                {
                    channel->sendMessage(who, text);
                }
            }
        }
    }
    else if (cmd == "PM")
    {
        if (list.length() == 3)
        {
            QByteArray name = list.at(1);
            QByteArray text = list.at(2);
            QLinkedList<AbsConnection*>::iterator it;
            for (it=m_connections.begin();it!=m_connections.end();++it)
            {
                AbsConnection * conn = (*it);
                if (conn->name() == name)
                {
                    conn->send(QVariantList() << "PM" << who->name() << text);
                    who->send(QVariantList() << "PM" << "OK" << text);
                    break;
                }
            }
            who->send(QVariantList() << "PM" << "ERR" << "NOT FOUND");
        }
    }
    else if (cmd == "UL")
    {
        if (list.length() == 2)
        {
            quint32 id = list.at(1).toInt();
            if (m_channels.contains(id))
            {
                Channel * channel = m_channels.value(id);
                who->send(QVariantList() << "UL" << id << channel->getUserList());
            }
        }
    }
}
コード例 #14
0
ファイル: users.c プロジェクト: ArNz8o8/undernet-cservice
void onnick(char *source, char *newnick, char *body)
{
  register aluser *user, **u;
  register asuser *suser, **s;
  register aserver *serv;
  char username[80];
  char hostname[80];
  char TS[80];
  char server[80];
  register achannelnode *chan;
  register anickchange *curr, *prec;
  char buffer[512];
  int i = 0;


#ifdef DEBUG
  printf("NICK: %s --> %s ...\n", source, newnick);
#endif

  /* a new user */
  if (!ToLuser(source))
  {	/* Not a user, so a server or nothing */
    if (strchr(source, '.') == NULL)
    {
      /* Source is not a user and not a server either */
      return;
    }

    if (!strcasecmp(newnick, mynick))
    {
      log("ERROR: I'm nick collided");
#ifdef DEBUG
      printf("ARGH!!! I'M NICK COLLIDED!\n");
#endif
      GetWord(1, body, TS);
      GetWord(2, body, username);
      GetWord(3, body, hostname);

      if (atol(TS) <= logTS &&
	strcasecmp(username, myuser) &&
	strcasecmp(hostname, mysite))
      {
	NickInUse();
	log(source);
	log(newnick);
	log(body);
      }
      else
      {
	onquit(source);
	return;		/*ignore */
      }
#ifdef BACKUP
    }
    else if (!strcasecmp(newnick, MAIN_NICK))
    {
      return;	/* ignore */
#endif
    }
    else if (ToLuser(newnick))
    {
#ifdef DEBUG
      printf("ARGH!!! NICK COLLISION\n");
#endif
      onquit(newnick);
    }
    GetWord(1, body, TS);
    GetWord(2, body, username);
    GetWord(3, body, hostname);
    GetWord(4, body, server);

#ifdef FAKE_UWORLD
    if (Uworld_status == 1 && !strcasecmp(newnick, UFAKE_NICK))
    {
      if (atol(TS) <= UworldTS && atol(TS) != 0 &&
	strcasecmp(username, UFAKE_NICK) &&
	strcasecmp(hostname, UFAKE_HOST))
      {
	sprintf(buffer, "%s nick collided", UFAKE_NICK);
	log(buffer);
	Uworld_status = 0;
	KillUworld("nick collision");
	return;		/* ignore if younger */
      }
    }
#endif

    user = (aluser *) MALLOC(sizeof(aluser));

    user->nick = (char *)MALLOC(strlen(newnick) + 1);
    strcpy(user->nick, newnick);

    user->username = (char *)MALLOC(strlen(username) + 1);
    strcpy(user->username, username);

    user->site = (char *)MALLOC(strlen(hostname) + 1);
    strcpy(user->site, hostname);

    if (*newnick == '+')
      serv = &VirtualServer;
    else
      serv = ToServer(server);

    user->server = serv;

    user->time = atol(TS);
    user->mode = 0;

    user->channel = NULL;
    user->valchan = NULL;

    user->next = Lusers[lu_hash(newnick)];
    Lusers[lu_hash(newnick)] = user;

    /* add user in server's userlist
     */
    suser = (asuser *) MALLOC(sizeof(asuser));
    suser->N = user;
    suser->next = serv->users[su_hash(newnick)];
    serv->users[su_hash(newnick)] = suser;

#ifdef NICKSERV
    nserv_nick(newnick, user);
#endif
  }
  else
  {	/* nick change */

#if 0
    if (!strcasecmp(source, DEFAULT_NICKNAME) &&
      strcasecmp(newnick, DEFAULT_NICKNAME))
    {
      ChNick(DEFAULT_NICKNAME);
    }
#endif
    if (!strcasecmp(newnick, mynick))
    {
#ifdef DEBUG
      printf("ARGH!!! I'M NICK COLLIDED!\n");
#endif
      GetWord(0, body, TS);
      if (atol(TS + 1) <= logTS)
      {
	NickInUse();
	log(source);
	log(newnick);
	log(body);
      }
      else
      {
	onquit(source);
	return;		/*ignore */
      }
    }

    u = &Lusers[lu_hash(source)];
    while (*u && strcasecmp(source, (*u)->nick))
      u = &(*u)->next;
    user = *u;

#ifdef NICKSERV
    nserv_nick(newnick, user);
#endif

    if (user == NULL)
      quit("ERROR! onnick() can't find user", 1);

    s = &user->server->users[su_hash(source)];
    while (*s && strcasecmp((*s)->N->nick, user->nick))
      s = &(*s)->next;
    suser = *s;

    /* change the nick in memory */

    TTLALLOCMEM -= strlen(user->nick) + 1;
    free(user->nick);
    user->nick = (char *)MALLOC(strlen(newnick) + 1);
    strcpy(user->nick, newnick);

    /* now relocate the structure */
    *u = user->next;
    user->next = Lusers[lu_hash(newnick)];
    Lusers[lu_hash(newnick)] = user;

    *s = suser->next;
    suser->next = user->server->users[su_hash(newnick)];
    user->server->users[su_hash(newnick)] = suser;

    /* NICK FLOOD PROTECTION */
    /* 1st wipe old nick changes off */
    chan = user->channel;
    while (chan)
    {
      curr = chan->nickhist;
      prec = NULL;

      /* if not on channel.. ignore nick flood pro */
      if (!chan->N->on)
      {
	chan = chan->next;
	continue;	/* yurk.. as bad as a goto ;) */
      }

      while (curr)
      {
	if (curr->time < (now - 15))
	{
	  if (prec)
	  {
	    prec->next = curr->next;
	    TTLALLOCMEM -= sizeof(anickchange);
	    free(curr);
	    curr = prec->next;
	  }
	  else
	  {
	    chan->nickhist = curr->next;
	    TTLALLOCMEM -= sizeof(anickchange);
	    free(curr);
	    curr = chan->nickhist;
	  }
	}
	else
	{
	  prec = curr;
	  curr = curr->next;
	}
      }

      /* now add the new nick change to the history */
      curr = (anickchange *) MALLOC(sizeof(anickchange));
      strcpy(curr->nick, source);
      curr->time = now;		/* a lil confusing :( */
      curr->next = chan->nickhist;
      chan->nickhist = curr;

      /* now count the nick changes in history
         if there are more than allowed.. grrrr */
      for (i = 0, curr = chan->nickhist; curr;
	curr = curr->next, i++);

      if (i == chan->N->NickFloodPro && chan->N->NickFloodPro != 0
	&& chan->N->on)
      {
	sprintf(buffer, "%s!%s@%s", user->nick, user->username, user->site);
	notice(newnick,
	  "### NICK FLOOD PROTECTION ACTIVATED ###");
	sprintf(buffer, "%s %d", newnick,
	  NICK_FLOOD_SUSPEND_TIME);
	suspend("", chan->N->name, buffer);
	ban("", chan->N->name, newnick);
      }
      chan = chan->next;
    }
  }
}
コード例 #15
0
ファイル: CKickBan.cpp プロジェクト: fizyk20/ircbot
void CKickBan::executeCommand(QString command, QStringList params, QString addr, QString sender)
{
	CUsers* users = (CUsers*) core -> getPlugin("users");
	if(command == "vote")
	{
		if(params.length() < 1) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
		if(params[0] == "pass_min")
		{
			if(params.length() < 2) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			settings -> SetDouble("vote_pass_min", params[1].toDouble());
			return;
		}
		if(params[0] == "timeout")
		{
			if(params.length() < 2) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			settings -> SetInt("vote_timeout", params[1].toInt());
			return;
		}
		if(params[0] == "min_votes")
		{
			if(params.length() < 2) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			settings -> SetInt("vote_min_votes", params[1].toInt());
			return;
		}
		return;
	}
	if(state == Waiting)
	{
		if(command == "kick")
		{
			if(params.length() < 1) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			if(params[0] == core -> getNick()) { core -> sendMsg(addr, "Nie będę kopał samego siebie ;)"); return; }
			if(users -> Find(params[0]) == -1) { core -> sendMsg(addr, "Nie ma takiego użytkownika!"); return; }

			core -> kickUser(params[0], (params.length() > 1) ? params[1] : "");
		}
		else if(command == "ban")
		{
			if(params.length() < 1) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			if(params[0] == core -> getNick()) { core -> sendMsg(addr, "Nie będę banował samego siebie ;)"); return; }
			int id = users -> Find(params[0]);
			if(id == -1) { core -> sendMsg(addr, "Nie ma takiego użytkownika."); return; }

			User u = (*users)[id];
			ban(u.nick, "*!" + u.mask);
			core -> kickUser(params[0], (params.length() > 1) ? params[1] : "");
		}
		else if(command == "unban")
		{
			if(params.length() < 1) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			if(! bans.contains(params[0])) { core -> sendMsg(addr, "Nie ma bana o takiej nazwie!"); return; }

			unban(params[0]);
		}
		else if(command == "banlist")
		{
			list_reply = addr;
			core -> channelMode("b", "");
		}

		/**** Votes ****/

		else if(command == "votekick")
		{
			if(params.length() < 1) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			if(params[0] == core -> getNick()) { core -> sendMsg(addr, "Nie będę kopał samego siebie ;)"); return; }
			if(users -> Find(params[0]) == -1) { core -> sendMsg(addr, "Nie ma takiego użytkownika!"); return; }

			voteTarget = params[0];
			int timeout = settings -> GetInt("vote_timeout");
			state = Voting;
			voteType = Kick;
			vote = new Vote;
			core -> sendMsgChannel("Głosowanie nad kickiem dla " + params[0] + ".");
			core -> sendMsgChannel("W ciągu następnych " + QString::number(timeout/1000) + " sekund wpisz \"!yes\" (głos za), \"!no\" (głos przeciw) albo \"!whatever\" (wstrzymanie się).");
			QTimer::singleShot(timeout, this, SLOT(endVote()));
		}
		else if(command == "voteban")
		{
			if(params.length() < 1) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			if(params[0] == core -> getNick()) { core -> sendMsg(addr, "Nie będę banował samego siebie ;)"); return; }
			int id = users -> Find(params[0]);
			if(id == -1) { core -> sendMsg(addr, "Nie ma takiego użytkownika!"); return; }

			voteTarget = params[0];
			voteMask = "*!*@" + (*users)[id].mask;
			int timeout = settings -> GetInt("vote_timeout");
			state = Voting;
			voteType = Ban;
			vote = new Vote;
			core -> sendMsgChannel("Głosowanie nad banem dla " + params[0] + ".");
			core -> sendMsgChannel("W ciągu następnych " + QString::number(timeout/1000) + " sekund wpisz \"!yes\" (głos za), \"!no\" (głos przeciw) albo \"!whatever\" (wstrzymanie się).");
			QTimer::singleShot(timeout, this, SLOT(endVote()));
		}
		else if(command == "voteunban")
		{
			if(params.length() < 1) { core -> sendMsg(addr, "Za mało parametrów!"); return; }
			if(! bans.contains(params[0])) { core -> sendMsg(addr, "Nie ma takiego bana!"); return; }

			voteTarget = params[0];
			int timeout = settings -> GetInt("vote_timeout");
			state = Voting;
			voteType = Unban;
			vote = new Vote;
			core -> sendMsgChannel("Głosowanie nad zdjęciem bana dla " + params[0] + ".");
			core -> sendMsgChannel("W ciągu następnych " + QString::number(timeout/1000) + " sekund wpisz \"!yes\" (głos za), \"!no\" (głos przeciw) albo \"!whatever\" (wstrzymanie się).");
			QTimer::singleShot(timeout, this, SLOT(endVote()));
		}
		else
		{
			core -> sendMsg(addr, "Ta komenda jest teraz nieaktywna.");
			return;
		}
	}
	else if(state == Voting)
	{
		if(command == "yes")
		{
			if(! vote -> voteFor(sender))
			{
				core -> sendMsg(addr, "Już głosowałeś/aś w tym głosowaniu!");
				return;
			}
			if(vote -> numVotes() == users -> presentUsers())
			{
				endVote();
				return;
			}
		}
		else if(command == "no")
		{
			if(! vote -> voteAgainst(sender))
			{
				core -> sendMsg(addr, "Już głosowałeś/aś w tym głosowaniu!");
				return;
			}
			if(vote -> numVotes() == users -> presentUsers())
			{
				endVote();
				return;
			}
		}
		else if(command == "whatever")
		{
			if(! vote -> voteNone(sender))
			{
				core -> sendMsg(addr, "Już głosowałeś/aś w tym głosowaniu!");
				return;
			}
			if(vote -> numVotes() == users -> presentUsers())
			{
				endVote();
				return;
			}
		}
		else
		{
			core -> sendMsg(addr, "Ta komenda jest teraz nieaktywna.");
			return;
		}
	}
}
コード例 #16
0
PlayersWindow::PlayersWindow(QWidget *parent, int expireDays)
    : QWidget (parent)
{
    setAttribute(Qt::WA_DeleteOnClose, true);
    resize(726, this->height());

    QGridLayout *mylayout = new QGridLayout(this);

    mytable = new QCompactTable(0,7);

    mytable->setShowGrid(true);
    mylayout->addWidget(mytable,0,0,1,6);

    QMap<int, QString> authgrade;
    authgrade[0] = "User";
    authgrade[1] = "Mod";
    authgrade[2] = "Admin";
    authgrade[3] = "Owner";

    QStringList headers;
    headers << "Player" << "Authority" << "Banned Status" << "Registered" << "IP" << "Last Appearance" << "Expires In";
    mytable->setHorizontalHeaderLabels(headers);

    QSqlQuery q;
    q.setForwardOnly(true);

    q.exec("select count(*) from trainers");

    if (q.next()) {
        mytable->setRowCount(q.value(0).toInt());
    }

    q.exec("select name, auth, banned, hash, ip, laston, ban_expire_time from trainers order by name asc");

    int i = 0;

    while(q.next()) {
        QTableWidgetItem *witem = new QTableWidgetItem(q.value(0).toString());
        mytable->setItem(i, 0, witem);

        witem = new QTableWidgetItem(authgrade[q.value(1).toInt()]);
        mytable->setItem(i, 1, witem);

        QString bannedString = "Banned";
        int expiration = q.value(6).toInt() - QDateTime::currentDateTimeUtc().toTime_t();
        if(expiration < 0) {
            if (q.value(6).toInt() != 0)
            bannedString = "Expires on Login";
        } else {
            if(expiration < 60) {
                if(expiration == 1) {
                    bannedString.append(QString(" (%1 second)").arg(expiration));
                } else {
                    bannedString.append(QString(" (%2 seconds)").arg(expiration));
                }
            } else {
                if(expiration >= 60) {
                    expiration = expiration / 60;
                    if(expiration == 1) {
                        bannedString.append(QString(" (%1 minute)").arg(expiration));
                    } else {
                        bannedString.append(QString(" (%2 minutes)").arg(expiration));
                    }
                }
            }
        }
        witem = new QTableWidgetItem(q.value(2).toBool() ? bannedString : "Fine");
        mytable->setItem(i, 2, witem);

        witem = new QTableWidgetItem(q.value(3).toString().length() > 0 ? "Yes" : "No");
        mytable->setItem(i, 3, witem);

        witem = new QTableWidgetItem(q.value(4).toString());
        mytable->setItem(i, 4, witem);

        witem = new QTableWidgetItem(q.value(5).toString());
        mytable->setItem(i, 5, witem);

        witem = new QTableWidgetItem(QString::number(expireDays - QDate::fromString(q.value(5).toString(), "yyyy-MM-dd").daysTo(QDate::currentDate())) + " Days");
        mytable->setItem(i, 6, witem);

        i++;
    }

    mytable->sortByColumn(0, Qt::AscendingOrder);

    mytable->setSortingEnabled(true);

    QPushButton *_authority = new QPushButton(tr("&Authority"));
    QMenu *m = new QMenu(_authority);
    m->addAction(tr("User"), this, SLOT(user()));
    m->addAction(tr("Moderator"), this, SLOT(mod()));
    m->addAction(tr("Administrator"), this, SLOT(admin()));
    m->addAction(tr("Owner"), this, SLOT(owner()));
    _authority->setMenu(m);

    QPushButton *_ban = new QPushButton(tr("&Ban"));
    QPushButton *_unban = new QPushButton(tr("U&nban"));
    QPushButton *_clpass = new QPushButton(tr("&Clear Password"));

    mylayout->addWidget(_authority,1,0);
    mylayout->addWidget(_ban,1,2);
    mylayout->addWidget(_unban,1,3);
    mylayout->addWidget(_clpass,1,4);

    if (mytable->rowCount() == 0)
        return;

    connect(_ban,SIGNAL(clicked()),SLOT(ban()));
    connect(_unban,SIGNAL(clicked()),SLOT(unban()));
    connect(_clpass,SIGNAL(clicked()),SLOT(clpass()));
}
コード例 #17
0
ファイル: kick.c プロジェクト: Cloudxtreme/atheme-6.0
static void cs_cmd_kickban(sourceinfo_t *si, int parc, char *parv[])
{
	char *chan = parv[0];
	char *nick = parv[1];
	char *reason = parv[2];
	mychan_t *mc;
	user_t *tu;
	chanuser_t *cu;
	char reasonbuf[BUFSIZE];
	int n;

	if (!chan || !nick)
	{
		command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "KICKBAN");
		command_fail(si, fault_needmoreparams, _("Syntax: KICKBAN <#channel> <nickname> [reason]"));
		return;
	}

	mc = mychan_find(chan);
	if (!mc)
	{
		command_fail(si, fault_nosuch_target, _("Channel \2%s\2 is not registered."), chan);
		return;
	}

	if (!chanacs_source_has_flag(mc, si, CA_REMOVE))
	{
		command_fail(si, fault_noprivs, _("You are not authorized to perform this operation."));
		return;
	}

	/* figure out who we're going to kick */
	if (!(tu = user_find_named(nick)))
	{
		command_fail(si, fault_nosuch_target, _("\2%s\2 is not online."), nick);
		return;
	}

        /* if target is a service, bail. --nenolod */
	if (is_internal_client(tu))
		return;

	cu = chanuser_find(mc->chan, tu);
	if (!cu)
	{
		command_fail(si, fault_nosuch_target, _("\2%s\2 is not on \2%s\2."), tu->nick, mc->name);
		return;
	}

	if (cu->modes & CSTATUS_OWNER || cu->modes & CSTATUS_PROTECT)
	{
		command_fail(si, fault_noprivs, _("\2%s\2 is protected from kicks; you cannot kick them."), tu->nick);
		return;
	}

	snprintf(reasonbuf, BUFSIZE, "(%s) %s", get_source_name(si), reason ? reason : "No reason given");
	ban(si->service->me, mc->chan, tu);
	n = remove_ban_exceptions(si->service->me, mc->chan, tu);
	if (n > 0)
		command_success_nodata(si, _("To avoid rejoin, %d ban exception(s) matching \2%s\2 have been removed from \2%s\2."), n, tu->nick, mc->name);
	try_kick(chansvs.me->me, mc->chan, tu, reasonbuf);
	logcommand(si, CMDLOG_DO, "KICKBAN: \2%s!%s@%s\2 from \2%s\2", tu->nick, tu->user, tu->vhost, mc->name);
	if (si->su != tu && !chanuser_find(mc->chan, si->su))
		command_success_nodata(si, _("\2%s\2 has been kickbanned from \2%s\2."), tu->nick, mc->name);
}
コード例 #18
0
ファイル: m_permchannels.cpp プロジェクト: GeeksIRC/inspircd
static bool WriteDatabase(PermChannel& permchanmode, Module* mod, bool save_listmodes)
{
	ChanModeReference ban(mod, "ban");
	/*
	 * We need to perform an atomic write so as not to f**k things up.
	 * So, let's write to a temporary file, flush it, then rename the file..
	 *     -- w00t
	 */

	// If the user has not specified a configuration file then we don't write one.
	if (permchannelsconf.empty())
		return true;

	std::string permchannelsnewconf = permchannelsconf + ".tmp";
	std::ofstream stream(permchannelsnewconf.c_str());
	if (!stream.is_open())
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot create database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", strerror(errno), errno);
		return false;
	}

	stream << "# This file is automatically generated by m_permchannels. Any changes will be overwritten." << std::endl
		<< "<config format=\"xml\">" << std::endl;

	for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->end(); i++)
	{
		Channel* chan = i->second;
		if (!chan->IsModeSet(permchanmode))
			continue;

		std::string chanmodes = chan->ChanModes(true);
		if (save_listmodes)
		{
			std::string modes;
			std::string params;

			const ModeParser::ListModeList& listmodes = ServerInstance->Modes->GetListModes();
			for (ModeParser::ListModeList::const_iterator j = listmodes.begin(); j != listmodes.end(); ++j)
			{
				ListModeBase* lm = *j;
				ListModeBase::ModeList* list = lm->GetList(chan);
				if (!list || list->empty())
					continue;

				size_t n = 0;
				// Append the parameters
				for (ListModeBase::ModeList::const_iterator k = list->begin(); k != list->end(); ++k, n++)
				{
					params += k->mask;
					params += ' ';
				}

				// Append the mode letters (for example "IIII", "gg")
				modes.append(n, lm->GetModeChar());
			}

			if (!params.empty())
			{
				// Remove the last space
				params.erase(params.end()-1);

				// If there is at least a space in chanmodes (that is, a non-listmode has a parameter)
				// insert the listmode mode letters before the space. Otherwise just append them.
				std::string::size_type p = chanmodes.find(' ');
				if (p == std::string::npos)
					chanmodes += modes;
				else
					chanmodes.insert(p, modes);

				// Append the listmode parameters (the masks themselves)
				chanmodes += ' ';
				chanmodes += params;
			}
		}

		stream << "<permchannels channel=\"" << ServerConfig::Escape(chan->name)
			<< "\" ts=\"" << chan->age
			<< "\" topic=\"" << ServerConfig::Escape(chan->topic)
			<< "\" topicts=\"" << chan->topicset
			<< "\" topicsetby=\"" << ServerConfig::Escape(chan->setby)
			<< "\" modes=\"" << ServerConfig::Escape(chanmodes)
			<< "\">" << std::endl;
	}

	if (stream.fail())
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot write to new database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno);
		return false;
	}
	stream.close();

#ifdef _WIN32
	if (remove(permchannelsconf.c_str()))
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot remove old database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot remove old database: %s (%d)", strerror(errno), errno);
		return false;
	}
#endif
	// Use rename to move temporary to new db - this is guarenteed not to f**k up, even in case of a crash.
	if (rename(permchannelsnewconf.c_str(), permchannelsconf.c_str()) < 0)
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot move new to old database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
		return false;
	}

	return true;
}
コード例 #19
0
static bool WriteDatabase(PermChannel& permchanmode, Module* mod, bool save_listmodes)
{
	ChanModeReference ban(mod, "ban");
	/*
	 * We need to perform an atomic write so as not to f**k things up.
	 * So, let's write to a temporary file, flush it, then rename the file..
	 *     -- w00t
	 */
	
	// If the user has not specified a configuration file then we don't write one.
	if (permchannelsconf.empty())
		return true;

	std::string permchannelsnewconf = permchannelsconf + ".tmp";
	std::ofstream stream(permchannelsnewconf.c_str());
	if (!stream.is_open())
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot create database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot create new db: %s (%d)", strerror(errno), errno);
		return false;
	}
	
	stream << "# This file is automatically generated by m_permchannels. Any changes will be overwritten." << std::endl
		<< "<config format=\"xml\">" << std::endl;

	for (chan_hash::const_iterator i = ServerInstance->chanlist->begin(); i != ServerInstance->chanlist->end(); i++)
	{
		Channel* chan = i->second;
		if (!chan->IsModeSet(permchanmode))
			continue;

		std::string chanmodes = chan->ChanModes(true);
		if (save_listmodes)
		{
			ListModeData lm;

			// Bans are managed by the core, so we have to process them separately
			static_cast<ListModeBase*>(*ban)->DoSyncChannel(chan, mod, &lm);

			// All other listmodes are managed by modules, so we need to ask them (call their
			// OnSyncChannel() handler) to give our ProtoSendMode() a list of modes that are
			// set on the channel. The ListModeData struct is passed as an opaque pointer
			// that will be passed back to us by the module handling the mode.
			FOREACH_MOD(OnSyncChannel, (chan, mod, &lm));

			if (!lm.modes.empty())
			{
				// Remove the last space
				lm.params.erase(lm.params.end()-1);

				// If there is at least a space in chanmodes (that is, a non-listmode has a parameter)
				// insert the listmode mode letters before the space. Otherwise just append them.
				std::string::size_type p = chanmodes.find(' ');
				if (p == std::string::npos)
					chanmodes += lm.modes;
				else
					chanmodes.insert(p, lm.modes);

				// Append the listmode parameters (the masks themselves)
				chanmodes += ' ';
				chanmodes += lm.params;
			}
		}

		stream << "<permchannels channel=\"" << ServerConfig::Escape(chan->name)
			<< "\" ts=\"" << chan->age
			<< "\" topic=\"" << ServerConfig::Escape(chan->topic)
			<< "\" topicts=\"" << chan->topicset
			<< "\" topicsetby=\"" << ServerConfig::Escape(chan->setby)
			<< "\" modes=\"" << ServerConfig::Escape(chanmodes)
			<< "\">" << std::endl;
	}

	if (stream.fail())
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot write to new database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot write to new db: %s (%d)", strerror(errno), errno);
		return false;
	}
	stream.close();

#ifdef _WIN32
	if (remove(permchannelsconf.c_str()))
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot remove old database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot remove old database: %s (%d)", strerror(errno), errno);
		return false;
	}
#endif
	// Use rename to move temporary to new db - this is guarenteed not to f**k up, even in case of a crash.
	if (rename(permchannelsnewconf.c_str(), permchannelsconf.c_str()) < 0)
	{
		ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Cannot move new to old database! %s (%d)", strerror(errno), errno);
		ServerInstance->SNO->WriteToSnoMask('a', "database: cannot replace old with new db: %s (%d)", strerror(errno), errno);
		return false;
	}

	return true;
}
コード例 #20
0
ファイル: icommand.cpp プロジェクト: Tomatix/IdealIRC
/*!
 * \param command A command to parse, for example "/join #channel key"
 *
 * \return true when command was found, false otherwise.\n Note that, even if a command fails to execute, true is still returned.
 */
bool ICommand::parse(QString command)
{
    /*
        This function must return true if the command was found, even if
        the command resulted in an error!
        ONLY return false if the command was not found.
    */

    if (command[0] == '/')
        command = command.mid(1);

    QStringList token = command.split(' ');
    QString t1 = token[0].toUpper();

    if (t1 == "JOIN") {
        if (! connection->isOnline()) {
            localMsg(NotConnectedToServer("/Join"));
            return true;
        }
        if (token.count() == 1) {
            localMsg(InsufficientParameters("/Join"));
            return true;
        }
        if (token.count() == 2) {
            join(token.at(1));
            return true;
        }
        QString pass = command.mid(t1.length() + token.at(1).length() + 2);
        join(token.at(1), pass);
        return true;
    }

    if (t1 == "PART") {
        if (! connection->isOnline()) {
            localMsg(NotConnectedToServer("/Part"));
            return true;
        }
        if (token.count() == 1) {
            localMsg(InsufficientParameters("/Part"));
            return true;
        }
        if (token.count() == 2) {
            part(token.at(1));
            return true;
        }
        QString reason = command.mid(t1.length() + token[1].length() + 2);
        part(token.at(1), reason);
        return true;
    }

    if (t1 == "QUIT") {
        QString reason;

        reason = command.mid(5);
        quit(reason);
    }

    if (t1 == "NOTICE") {
        if (! connection->isOnline()) {
            localMsg(NotConnectedToServer("/Notice"));
            return true;
        }
        if (token.count() < 3) {
            localMsg(InsufficientParameters("/Notice"));
            return true;
        }
        QString text = command.mid(token[1].length()+8);
        notice(token[1], text);
        return true;
    }

    if (t1 == "MSG") {
        if (! connection->isOnline()) {
            localMsg(NotConnectedToServer("/Msg"));
            return true;
        }
        if (token.count() < 3) {
            localMsg(InsufficientParameters("/Msg"));
            return true;
        }
        QString text = command.mid(token[1].length()+5);
        msg(token[1], text);
        return true;
    }

    if (t1 == "ME") {
        if (! connection->isOnline()) {
            localMsg(NotConnectedToServer("/Me"));
            return true;
        }
        subwindow_t wt = winlist->value(activewin());
        if ((wt.type != WT_CHANNEL) && (wt.type != WT_PRIVMSG)) {
            localMsg(tr("You're not in a chat window!"));
            return true;
        }
        QString target = wt.widget->getTarget();
        me(target, command.mid(3));
        return true;
    }

    if (t1 == "CTCP") {
        if (! connection->isOnline()) {
            localMsg(NotConnectedToServer("/Ctcp"));
            return true;
        }

        if (token.count() < 3) {
            localMsg(InsufficientParameters("/Ctcp"));
            return true;
        }

        // /ctcp target msg param param param ...

        int skip = 0;
        for (int i = 0; i <= 1; ++i)
            skip += token[i].length() + 1;
        QString msg = command.mid(skip).toUpper();

        if (msg == "PING") {
            QString ms = QString::number( QDateTime::currentMSecsSinceEpoch() );
            msg += ' ';
            msg += ms;
        }

        ctcp(token[1], msg);
        return true;
    }

    if (t1 == "KICK") {
        // kick #chan nick [reason]
        if (token.count() < 2) {
            localMsg(InsufficientParameters("/Kick"));
            return true;
        }
        QString channel = token[1];
        QString nickname;
        int l = 5;
        if (! connection->isValidChannel(channel)) {
            channel.clear();
            nickname = token[1];
            l += nickname.length() + 1;
        }
        else {
            nickname = token[2];
            l += nickname.length() + channel.length() + 2;
        }

        QString reason = command.mid(l);

        kick(channel, nickname, reason);

        return true;
    }

    if (t1 == "KILL") {
        if (token.count() < 2) {
            localMsg(InsufficientParameters("/Kill"));
            return true;
        }
        QString nickname = token[1];
        QString reason = command.mid(nickname.length() + 5);

        kill(nickname, reason);
        return true;
    }

    if (t1 == "BAN") {
        if (token.count() < 2) {
            localMsg(InsufficientParameters("/Ban"));
            return true;
        }

        QString channel = token[1];
        QString nickname;
        if (token.count() == 2) {
            channel.clear();
            nickname = token[1];
        }
        else
            nickname = token[2];

        ban(channel, nickname);
        return true;
    }

    if ((t1 == "RAW") || (t1 == "QUOTE")) {
        if (! connection->isOnline()) {
            localMsg( tr("/%1: Not connected to server.")
                     .arg(t1)
                  );
            return true;
        }
        if (token.count() < 2) {
            localMsg( tr("/%1: Insufficient parameters.")
                     .arg(t1)
                  );
            return true;
        }
        QString c = command.mid(t1.length()+1);
        raw(c);
        return true;
    }

    if (t1 == "CHARSET") {
        if (token.count() < 2) {
            localMsg( tr("/Charset: Current set is '%1'")
                     .arg(conf->charset));
            return true;
        }

        charset(token[1]);
        return true;
    }

    if (t1 == "CLEAR") {
        if (token.count() == 1) {
            // clear active window
        }

        subwindow_t sw = getCurrentSubwin();
        if (sw.type == WT_NOTHING)
            return true;
        sw.widget->clear();
        return true;
    }

    if (t1 == "PING") {
        if (! connection->isOnline()) {
            localMsg(NotConnectedToServer("/Ping"));
            return true;
        }
        ping();
        return true;
    }

    if (t1 == "QUERY") {
        if (token.count() < 2) {
            localMsg(InsufficientParameters("/Query"));
            return true;
        }

        query(token[1]);
        return true;
    }

    if (t1 == "CHANSETTINGS") {
        chansettings();
        return true;
    }

    return false; // Command wasn't found.
}
コード例 #21
0
void HWChatWidget::onBan()
{
    QListWidgetItem * curritem = chatNicks->currentItem();
    if (curritem)
        emit ban(curritem->text());
}