Пример #1
0
Serializable* ChanAccess::Unserialize(Serializable *obj, Serialize::Data &data)
{
	Anope::string provider, chan;

	data["provider"] >> provider;
	data["ci"] >> chan;

	ServiceReference<AccessProvider> aprovider("AccessProvider", provider);
	ChannelInfo *ci = ChannelInfo::Find(chan);
	if (!aprovider || !ci)
		return NULL;

	ChanAccess *access;
	if (obj)
		access = anope_dynamic_static_cast<ChanAccess *>(obj);
	else
		access = aprovider->Create();
	access->ci = ci;
	Anope::string m;
	data["mask"] >> m;
	access->SetMask(m, ci);
	data["creator"] >> access->creator;
	data["last_seen"] >> access->last_seen;
	data["created"] >> access->created;

	Anope::string adata;
	data["data"] >> adata;
	access->AccessUnserialize(adata);

	if (!obj)
		ci->AddAccess(access);
	return access;
}
Пример #2
0
	void Tick(time_t)
	{
		if (!Config->CSExpire || noexpire || readonly)
			return;

		for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end; )
		{
			ChannelInfo *ci = it->second;
			++it;

			bool expire = false;

			if (!ci->c && Config->CSExpire && Anope::CurTime - ci->last_used >= Config->CSExpire)
				expire = true;

			if (ci->HasFlag(CI_NO_EXPIRE))
				expire = false;

			FOREACH_MOD(I_OnPreChanExpire, OnPreChanExpire(ci, expire));

			if (expire)
			{
				Anope::string extra;
				if (ci->HasFlag(CI_SUSPENDED))
					extra = "suspended ";

				Log(LOG_NORMAL, "chanserv/expire") << "Expiring " << extra  << "channel " << ci->name << " (founder: " << (ci->GetFounder() ? ci->GetFounder()->display : "(none)") << ")";
				FOREACH_MOD(I_OnChanExpire, OnChanExpire(ci));
				delete ci;
			}
		}
	}
Пример #3
0
void ChanAccess::SetMask(const Anope::string &m, ChannelInfo *c)
{
	if (*nc != NULL)
		nc->RemoveChannelReference(this->ci);
	else if (!this->mask.empty())
	{
		ChannelInfo *targc = ChannelInfo::Find(this->mask);
		if (targc)
			targc->RemoveChannelReference(this->ci->name);
	}

	ci = c;
	mask.clear();
	nc = NULL;

	const NickAlias *na = NickAlias::Find(m);
	if (na != NULL)
	{
		nc = na->nc;
		nc->AddChannelReference(ci);
	}
	else
	{
		mask = m;

		ChannelInfo *targci = ChannelInfo::Find(mask);
		if (targci != NULL)
			targci->AddChannelReference(ci->name);
	}
}
Пример #4
0
void ChannelRecPriority::updateInfo(MythUIButtonListItem *item)
{
    if (!item)
        return;

    ChannelInfo *channelItem = item->GetData().value<ChannelInfo *>();
    if (!m_channelData.isEmpty() && channelItem)
    {
        QString rectype;
        if (m_iconImage)
        {
            QString iconUrl = gCoreContext->GetMasterHostPrefix("ChannelIcons", channelItem->icon);
            m_iconImage->SetFilename(iconUrl);
            m_iconImage->Load();
        }

        InfoMap chanmap;
        channelItem->ToMap(chanmap);
        SetTextFromMap(chanmap);

        if (m_chanstringText)
            m_chanstringText->SetText(channelItem->GetFormatted(ChannelInfo::kChannelLong));
    }

    MythUIText *norecordingText = dynamic_cast<MythUIText*>
                                                (GetChild("norecordings_info"));

    if (norecordingText)
        norecordingText->SetVisible(m_channelData.isEmpty());
}
Пример #5
0
	void Execute(CommandSource &source, const std::vector<Anope::string> &params)
	{
		const Anope::string &chan = params[0];

		User *u = source.u;
		Channel *c = findchan(chan);

		if (!c)
		{
			source.Reply(CHAN_X_NOT_IN_USE, chan.c_str());
			return;
		}

		ChannelInfo *ci = c->ci;
		if (!ci)
		{
			source.Reply(CHAN_X_NOT_REGISTERED, chan.c_str());
			return;
		}

		if (!ci->AccessFor(u).HasPriv("INVITE") && !u->HasCommand("chanserv/invite"))
		{
			source.Reply(ACCESS_DENIED);
			return;
		}

		User *u2;
		if (params.size() == 1)
			u2 = u;
		else
		{
			if (!(u2 = finduser(params[1])))
			{
				source.Reply(NICK_X_NOT_IN_USE, params[1].c_str());
				return;
			}
		}

		if (c->FindUser(u2))
		{
			if (u2 == u)
				source.Reply(_("You are already in \002%s\002!"), c->name.c_str());
			else
				source.Reply(_("\002%s\002 is already in \002%s\002!"), u2->nick.c_str(), c->name.c_str());
		}
		else
		{
			bool override = !ci->AccessFor(u).HasPriv("INVITE");

			ircdproto->SendInvite(ci->WhoSends(), chan, u2->nick);
			if (u2 != u)
			{
				source.Reply(_("\002%s\002 has been invited to \002%s\002."), u2->nick.c_str(), c->name.c_str());
				Log(override ? LOG_OVERRIDE : LOG_COMMAND, u, this, ci) << "for " << u2->nick;
			}
			else
			{
Пример #6
0
void ChannelRecPriority::FillList(void)
{
    QMap<int, QString> srcMap;

    m_channelData.clear();
    m_sortedChannel.clear();

    MSqlQuery result(MSqlQuery::InitCon());
    result.prepare("SELECT sourceid, name FROM videosource;");

    if (result.exec())
    {
        while (result.next())
        {
            srcMap[result.value(0).toInt()] = result.value(1).toString();
        }
    }
    result.prepare("SELECT chanid, channum, sourceid, callsign, "
                   "icon, recpriority, name FROM channel WHERE visible=1;");

    if (result.exec())
    {
        int cnt = 999;
        while (result.next())
        {
            ChannelInfo *chaninfo = new ChannelInfo;
            chaninfo->chanid = result.value(0).toInt();
            chaninfo->channum = result.value(1).toString();
            chaninfo->sourceid = result.value(2).toInt();
            chaninfo->callsign = result.value(3).toString();
            QString iconurl = result.value(4).toString();
            if (!iconurl.isEmpty())
                iconurl = gCoreContext->GetMasterHostPrefix( "ChannelIcons", iconurl);
            chaninfo->icon = iconurl;
            chaninfo->recpriority = result.value(5).toInt();
            chaninfo->name = result.value(6).toString();

            chaninfo->SetSourceName(srcMap[chaninfo->sourceid]);

            m_channelData[QString::number(cnt)] = *chaninfo;

            // save recording priority value in map so we don't have to save
            // all channel's recording priority values when we exit
            m_origRecPriorityData[QString::number(chaninfo->chanid)] =
                    chaninfo->recpriority;

            cnt--;
        }
    }
    else if (!result.isActive())
        MythDB::DBError("Get channel recording priorities query", result);

    SortList();
}
Пример #7
0
bool FillChannelInfo( DTC::ChannelInfo *pChannel,
                      uint              nChanID,
                      bool              bDetails  /* = true */ )
{
    ChannelInfo channel;
    if (channel.Load(nChanID))
    {
        return FillChannelInfo(pChannel, channel, bDetails);
    }

    return false;
}
Пример #8
0
bool ChanAccess::Matches(const User *u, const NickCore *acc, Path &p) const
{
	if (this->nc)
		return this->nc == acc;

	if (u)
	{
		bool is_mask = this->mask.find_first_of("!@?*") != Anope::string::npos;
		if (is_mask && Anope::Match(u->nick, this->mask))
			return true;
		else if (Anope::Match(u->GetDisplayedMask(), this->mask))
			return true;
	}
	
	if (acc)
	{
		for (unsigned i = 0; i < acc->aliases->size(); ++i)
		{
			const NickAlias *na = acc->aliases->at(i);
			if (Anope::Match(na->nick, this->mask))
				return true;
		}
	}
	
	if (IRCD->IsChannelValid(this->mask))
	{
		ChannelInfo *tci = ChannelInfo::Find(this->mask);
		if (tci)
		{
			for (unsigned i = 0; i < tci->GetAccessCount(); ++i)
			{
				ChanAccess *a = tci->GetAccess(i);
				std::pair<const ChanAccess *, const ChanAccess *> pair = std::make_pair(this, a);

				std::pair<Set::iterator, Set::iterator> range = p.first.equal_range(this);
				for (; range.first != range.second; ++range.first)
					if (range.first->first == pair.first && range.first->second == pair.second)
						goto cont;

				p.first.insert(pair);
				if (a->Matches(u, acc, p))
					p.second.insert(pair);

				cont:;
			}

			return p.second.count(this) > 0;
		}
	}
	
	return false;
}
Пример #9
0
void EntryMsg::unserialize(serialized_data &data)
{
	ChannelInfo *ci = cs_findchan(data["ci"].astr());
	if (!ci)
		return;

	EntryMessageList *messages = ci->GetExt<EntryMessageList *>("cs_entrymsg");
	if (messages == NULL)
	{
		messages = new EntryMessageList();
		ci->Extend("cs_entrymsg", messages);
	}

	messages->push_back(EntryMsg(ci, data["creator"].astr(), data["message"].astr()));
}
Пример #10
0
void ChannelRecPriority::updateList()
{
    m_channelList->Reset();

    QMap<QString, ChannelInfo*>::Iterator it;
    MythUIButtonListItem *item;
    for (it = m_sortedChannel.begin(); it != m_sortedChannel.end(); ++it)
    {
        ChannelInfo *chanInfo = *it;

        item = new MythUIButtonListItem(m_channelList, "",
                                                   qVariantFromValue(chanInfo));

        QString fontState = "default";
        if (!m_visMap[chanInfo->chanid])
            fontState = "disabled";

        QString stringFormat = item->GetText();
        if (stringFormat.isEmpty())
            stringFormat = "<num>  <sign>  \"<name>\"";
        item->SetText(chanInfo->GetFormatted(stringFormat), fontState);

        item->SetText(chanInfo->chanstr, "channum", fontState);
        item->SetText(chanInfo->callsign, "callsign", fontState);
        item->SetText(chanInfo->channame, "name", fontState);
        item->SetText(QString().setNum(chanInfo->sourceid), "sourceid",
                        fontState);
        item->SetText(chanInfo->sourcename, "sourcename", fontState);
        if (m_visMap[chanInfo->chanid])
            item->DisplayState("normal", "status");
        else
            item->DisplayState("disabled", "status");

        item->SetImage(chanInfo->iconpath, "icon");
        item->SetImage(chanInfo->iconpath);

        item->SetText(chanInfo->recpriority, "priority", fontState);

        if (m_currentItem == chanInfo)
            m_channelList->SetItemCurrent(item);
    }

    MythUIText *norecordingText = dynamic_cast<MythUIText*>
                                                (GetChild("norecordings_info"));

    if (norecordingText)
        norecordingText->SetVisible(m_channelData.isEmpty());
}
Пример #11
0
void ChannelRecPriority::updateList()
{
    m_channelList->Reset();

    QMap<QString, ChannelInfo*>::Iterator it;
    for (it = m_sortedChannel.begin(); it != m_sortedChannel.end(); ++it)
    {
        ChannelInfo *chanInfo = *it;

        MythUIButtonListItem *item =
               new MythUIButtonListItem(m_channelList, "",
                                                   qVariantFromValue(chanInfo));

        QString fontState = "default";

        item->SetText(chanInfo->GetFormatted(ChannelInfo::kChannelLong),
                                             fontState);

        InfoMap infomap;
        chanInfo->ToMap(infomap);
        item->SetTextFromMap(infomap, fontState);

        item->DisplayState("normal", "status");

        if (!chanInfo->icon.isEmpty())
        {
            QString iconUrl = gCoreContext->GetMasterHostPrefix("ChannelIcons",
                                                                chanInfo->icon);
            item->SetImage(iconUrl, "icon");
            item->SetImage(iconUrl);
        }

        item->SetText(QString::number(chanInfo->recpriority), "priority", fontState);

        if (m_currentItem == chanInfo)
            m_channelList->SetItemCurrent(item);
    }

    // this textarea name is depreciated use 'nochannels_warning' instead
    MythUIText *noChannelsText = dynamic_cast<MythUIText*>(GetChild("norecordings_info"));

    if (!noChannelsText)
        noChannelsText = dynamic_cast<MythUIText*>(GetChild("nochannels_warning"));

    if (noChannelsText)
        noChannelsText->SetVisible(m_channelData.isEmpty());
}
Пример #12
0
void BuildChanList(NickAlias *na, TemplateFileServer::Replacements &replacements)
{
	std::deque<ChannelInfo *> queue;
	na->nc->GetChannelReferences(queue);
	std::sort(queue.begin(), queue.end(), ChannelSort);

	for (unsigned i = 0; i < queue.size(); ++i)
	{
		ChannelInfo *ci = queue[i];

		if (na->nc != ci->GetFounder() && ci->AccessFor(na->nc).empty())
			continue;

		replacements["CHANNEL_NAMES"] = ci->name;
		replacements["ESCAPED_CHANNEL_NAMES"] = HTTPUtils::URLEncode(ci->name);
	}
}
Пример #13
0
ChanAccess::~ChanAccess()
{
	if (this->ci)
	{
		std::vector<ChanAccess *>::iterator it = std::find(this->ci->access->begin(), this->ci->access->end(), this);
		if (it != this->ci->access->end())
			this->ci->access->erase(it);

		if (*nc != NULL)
			nc->RemoveChannelReference(this->ci);
		else
		{
			ChannelInfo *c = ChannelInfo::Find(this->mask);
			if (c)
				c->RemoveChannelReference(this->ci->name);
		}
	}
}
Пример #14
0
void ChannelRecPriority::updateList()
{
    m_channelList->Reset();

    QMap<QString, ChannelInfo*>::Iterator it;
    MythUIButtonListItem *item;
    for (it = m_sortedChannel.begin(); it != m_sortedChannel.end(); ++it)
    {
        ChannelInfo *chanInfo = *it;

        item = new MythUIButtonListItem(m_channelList, "",
                                                   qVariantFromValue(chanInfo));

        QString fontState = "default";
        if (!m_visMap[chanInfo->chanid])
            fontState = "disabled";

        item->SetText(chanInfo->GetFormatted(ChannelInfo::kChannelLong),
                                             fontState);

        InfoMap infomap;
        chanInfo->ToMap(infomap);
        item->SetTextFromMap(infomap, fontState);

        if (m_visMap[chanInfo->chanid])
            item->DisplayState("normal", "status");
        else
            item->DisplayState("disabled", "status");

        item->SetImage(chanInfo->iconpath, "icon");
        item->SetImage(chanInfo->iconpath);

        item->SetText(chanInfo->recpriority, "priority", fontState);

        if (m_currentItem == chanInfo)
            m_channelList->SetItemCurrent(item);
    }

    MythUIText *norecordingText = dynamic_cast<MythUIText*>
                                                (GetChild("norecordings_info"));

    if (norecordingText)
        norecordingText->SetVisible(m_channelData.isEmpty());
}
Пример #15
0
void PrivateTab::channel(const ChannelInfo &info)
{
  if (info.id() != id())
    return;

  if (m_joined)
    return;

  m_chatView->add(ServiceMessage::joined(id()));
  m_joined = true;
}
Пример #16
0
bool WebCPanel::NickServ::Alist::OnRequest(HTTPProvider *server, const Anope::string &page_name, HTTPClient *client, HTTPMessage &message, HTTPReply &reply, NickAlias *na, TemplateFileServer::Replacements &replacements)
{
	std::deque<ChannelInfo *> queue;
	na->nc->GetChannelReferences(queue);
	std::sort(queue.begin(), queue.end(), ChannelSort);

	int chan_count = 0;

	for (unsigned q = 0; q < queue.size(); ++q)
	{
		ChannelInfo *ci = queue[q];

		if (ci->GetFounder() == na->nc)
		{
			++chan_count;

			replacements["NUMBERS"] = stringify(chan_count);
			replacements["CHANNELS"] = (ci->HasExt("CS_NO_EXPIRE") ? "!" : "") + ci->name;
			replacements["ACCESSES"] = "Founder";
			continue;
		}

		AccessGroup access = ci->AccessFor(na->nc);
		if (access.empty())
			continue;
				
		++chan_count;

		replacements["NUMBERS"] = stringify(chan_count);
		replacements["CHANNELS"] = (ci->HasExt("CS_NO_EXPIRE") ? "!" : "") + ci->name;
		Anope::string access_str;
		for (unsigned i = 0; i < access.size(); ++i)
			access_str += ", " + access[i]->AccessSerialize();
		replacements["ACCESSES"] = access_str.substr(2);
	}

	TemplateFileServer page("nickserv/alist.html");
	page.Serve(server, page_name, client, message, reply, replacements);
	return true;
}
Пример #17
0
void ChannelRecPriority::updateInfo(MythUIButtonListItem *item)
{
    if (!item)
        return;

    ChannelInfo *channelItem = qVariantValue<ChannelInfo *>(item->GetData());
    if (!m_channelData.isEmpty() && channelItem)
    {
        QString rectype;
        if (m_iconImage)
        {
            m_iconImage->SetFilename(channelItem->iconpath);
            m_iconImage->Load();
        }

        if (m_chanstringText)
            m_chanstringText->SetText(channelItem->GetFormatted(m_longchannelformat));
        if (m_callsignText)
            m_callsignText->SetText(channelItem->callsign);
        if (m_channumText)
            m_channumText->SetText(channelItem->chanstr);
        if (m_channameText)
            m_channameText->SetText(channelItem->channame);
        if (m_sourcenameText)
            m_sourcenameText->SetText(channelItem->sourcename);
        if (m_sourceidText)
            m_sourceidText->SetText(QString().setNum(channelItem->sourceid));
        if (m_priorityText)
            m_priorityText->SetText(channelItem->recpriority);
    }

    MythUIText *norecordingText = dynamic_cast<MythUIText*>
                                                (GetChild("norecordings_info"));

    if (norecordingText)
        norecordingText->SetVisible(m_channelData.isEmpty());
}
Пример #18
0
/*static*/ already_AddRefed<Response>
Response::Constructor(const GlobalObject& aGlobal,
                      const Optional<Nullable<fetch::ResponseBodyInit>>& aBody,
                      const ResponseInit& aInit, ErrorResult& aRv)
{
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());

  if (aInit.mStatus < 200 || aInit.mStatus > 599) {
    aRv.ThrowRangeError<MSG_INVALID_RESPONSE_STATUSCODE_ERROR>();
    return nullptr;
  }

  // Check if the status text contains illegal characters
  nsACString::const_iterator start, end;
  aInit.mStatusText.BeginReading(start);
  aInit.mStatusText.EndReading(end);
  if (FindCharInReadable('\r', start, end)) {
    aRv.ThrowTypeError<MSG_RESPONSE_INVALID_STATUSTEXT_ERROR>();
    return nullptr;
  }
  // Reset iterator since FindCharInReadable advances it.
  aInit.mStatusText.BeginReading(start);
  if (FindCharInReadable('\n', start, end)) {
    aRv.ThrowTypeError<MSG_RESPONSE_INVALID_STATUSTEXT_ERROR>();
    return nullptr;
  }

  RefPtr<InternalResponse> internalResponse =
    new InternalResponse(aInit.mStatus, aInit.mStatusText);

  // Grab a valid channel info from the global so this response is 'valid' for
  // interception.
  if (NS_IsMainThread()) {
    ChannelInfo info;
    nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(global);
    if (window) {
      nsIDocument* doc = window->GetExtantDoc();
      MOZ_ASSERT(doc);
      info.InitFromDocument(doc);
    } else {
      info.InitFromChromeGlobal(global);
    }
    internalResponse->InitChannelInfo(info);
  } else {
    WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(worker);
    internalResponse->InitChannelInfo(worker->GetChannelInfo());
  }

  RefPtr<Response> r = new Response(global, internalResponse, nullptr);

  if (aInit.mHeaders.WasPassed()) {
    internalResponse->Headers()->Clear();

    // Instead of using Fill, create an object to allow the constructor to
    // unwrap the HeadersInit.
    RefPtr<Headers> headers =
      Headers::Create(global, aInit.mHeaders.Value(), aRv);
    if (aRv.Failed()) {
      return nullptr;
    }

    internalResponse->Headers()->Fill(*headers->GetInternalHeaders(), aRv);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  }

  if (aBody.WasPassed() && !aBody.Value().IsNull()) {
    if (aInit.mStatus == 204 || aInit.mStatus == 205 || aInit.mStatus == 304) {
      aRv.ThrowTypeError<MSG_RESPONSE_NULL_STATUS_WITH_BODY>();
      return nullptr;
    }

    nsCString contentTypeWithCharset;
    nsCOMPtr<nsIInputStream> bodyStream;
    int64_t bodySize = InternalResponse::UNKNOWN_BODY_SIZE;

    const fetch::ResponseBodyInit& body = aBody.Value().Value();
    if (body.IsReadableStream()) {
      aRv.MightThrowJSException();

      JSContext* cx = aGlobal.Context();
      const ReadableStream& readableStream = body.GetAsReadableStream();

      JS::Rooted<JSObject*> readableStreamObj(cx, readableStream.Obj());

      bool disturbed;
      bool locked;
      if (!JS::ReadableStreamIsDisturbed(cx, readableStreamObj, &disturbed) ||
          !JS::ReadableStreamIsLocked(cx, readableStreamObj, &locked)) {
        aRv.StealExceptionFromJSContext(cx);
        return nullptr;
      }
      if (disturbed || locked) {
        aRv.ThrowTypeError<MSG_FETCH_BODY_CONSUMED_ERROR>();
        return nullptr;
      }

      r->SetReadableStreamBody(cx, readableStreamObj);

      JS::ReadableStreamMode streamMode;
      if (!JS::ReadableStreamGetMode(cx, readableStreamObj, &streamMode)) {
        aRv.StealExceptionFromJSContext(cx);
        return nullptr;
      }
      if (streamMode == JS::ReadableStreamMode::ExternalSource) {
        // If this is a DOM generated ReadableStream, we can extract the
        // inputStream directly.
        void* underlyingSource = nullptr;
        if (!JS::ReadableStreamGetExternalUnderlyingSource(cx,
                                                           readableStreamObj,
                                                           &underlyingSource)) {
          aRv.StealExceptionFromJSContext(cx);
          return nullptr;
        }

        MOZ_ASSERT(underlyingSource);

        aRv = FetchStream::RetrieveInputStream(underlyingSource,
                                               getter_AddRefs(bodyStream));

        // The releasing of the external source is needed in order to avoid an
        // extra stream lock.
        if (!JS::ReadableStreamReleaseExternalUnderlyingSource(cx, readableStreamObj)) {
          aRv.StealExceptionFromJSContext(cx);
          return nullptr;
        }
        if (NS_WARN_IF(aRv.Failed())) {
          return nullptr;
        }
      } else {
        // If this is a JS-created ReadableStream, let's create a
        // FetchStreamReader.
        aRv = FetchStreamReader::Create(aGlobal.Context(), global,
                                        getter_AddRefs(r->mFetchStreamReader),
                                        getter_AddRefs(bodyStream));
        if (NS_WARN_IF(aRv.Failed())) {
          return nullptr;
        }
      }
    } else {
      uint64_t size = 0;
      aRv = ExtractByteStreamFromBody(body,
                                      getter_AddRefs(bodyStream),
                                      contentTypeWithCharset,
                                      size);
      if (NS_WARN_IF(aRv.Failed())) {
        return nullptr;
      }

      bodySize = size;
    }

    internalResponse->SetBody(bodyStream, bodySize);

    if (!contentTypeWithCharset.IsVoid() &&
        !internalResponse->Headers()->Has(NS_LITERAL_CSTRING("Content-Type"),
                                          aRv)) {
      // Ignore Append() failing here.
      ErrorResult error;
      internalResponse->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"),
                                          contentTypeWithCharset, error);
      error.SuppressException();
    }

    if (aRv.Failed()) {
      return nullptr;
    }
  }

  r->SetMimeType();
  return r.forget();
}
Пример #19
0
	void Execute(CommandSource &source, const std::vector<Anope::string> &params)
	{
		const Anope::string &chan = params[0];
		const Anope::string &chdesc = params.size() > 1 ? params[1] : "";

		User *u = source.u;
		Channel *c = findchan(params[0]);
		ChannelInfo *ci = cs_findchan(params[0]);

		if (readonly)
			source.Reply(_("Sorry, channel registration is temporarily disabled."));
		else if (u->Account()->HasFlag(NI_UNCONFIRMED))
			source.Reply(_("You must confirm your account before you can register a channel."));
		else if (chan[0] == '&')
			source.Reply(_("Local channels cannot be registered."));
		else if (chan[0] != '#')
			source.Reply(CHAN_SYMBOL_REQUIRED);
		else if (!ircdproto->IsChannelValid(chan))
			source.Reply(CHAN_X_INVALID, chan.c_str());
		else if (ci)
			source.Reply(_("Channel \002%s\002 is already registered!"), chan.c_str());
		else if (c && !c->HasUserStatus(u, CMODE_OP))
			source.Reply(_("You must be a channel operator to register the channel."));
		else if (Config->CSMaxReg && u->Account()->channelcount >= Config->CSMaxReg && !u->HasPriv("chanserv/no-register-limit"))
			source.Reply(u->Account()->channelcount > Config->CSMaxReg ? CHAN_EXCEEDED_CHANNEL_LIMIT : _(CHAN_REACHED_CHANNEL_LIMIT), Config->CSMaxReg);
		else
		{
			ci = new ChannelInfo(chan);
			ci->SetFounder(u->Account());
			if (!chdesc.empty())
				ci->desc = chdesc;

			ci->mode_locks = def_mode_locks;
			for (ChannelInfo::ModeList::iterator it = ci->mode_locks.begin(), it_end = ci->mode_locks.end(); it != it_end; ++it)
			{
				it->second.setter = u->nick;
				it->second.ci = ci;
			}

			if (c && !c->topic.empty())
			{
				ci->last_topic = c->topic;
				ci->last_topic_setter = c->topic_setter;
				ci->last_topic_time = c->topic_time;
			}
			else
				ci->last_topic_setter = source.owner->nick;

			Log(LOG_COMMAND, u, this, ci);
			source.Reply(_("Channel \002%s\002 registered under your nickname: %s"), chan.c_str(), u->nick.c_str());

			/* Implement new mode lock */
			if (c)
			{
				check_modes(c);

				ChannelMode *cm;
				if (u->FindChannel(c) != NULL)
				{
					/* On most ircds you do not receive the admin/owner mode till its registered */
					if ((cm = ModeManager::FindChannelModeByName(CMODE_OWNER)))
						c->SetMode(NULL, cm, u->nick);
					else if ((cm = ModeManager::FindChannelModeByName(CMODE_PROTECT)))
						c->RemoveMode(NULL, cm, u->nick);
				}

				/* Mark the channel as persistent */
				if (c->HasMode(CMODE_PERM))
					ci->SetFlag(CI_PERSIST);
				/* Persist may be in def cflags, set it here */
				else if (ci->HasFlag(CI_PERSIST) && (cm = ModeManager::FindChannelModeByName(CMODE_PERM)))
					c->SetMode(NULL, CMODE_PERM);
			}

			FOREACH_MOD(I_OnChanRegistered, OnChanRegistered(ci));
		}
		return;
	}
Пример #20
0
Nrrd* OIFReader::Convert(int t, int c, bool get_max)
{
   Nrrd *data = 0;
   int sl_num = 0;

   if (t>=0 && t<m_time_num &&
         c>=0 && c<m_chan_num &&
         m_slice_num>0 &&
         m_x_size>0 &&
         m_y_size>0)
   {
      //allocate memory for nrrd
      unsigned long long mem_size = (unsigned long long)m_x_size*
         (unsigned long long)m_y_size*(unsigned long long)m_slice_num;
      unsigned short *val = new (std::nothrow) unsigned short[mem_size];

      //read the channel
      ChannelInfo *cinfo = &m_oif_info[t].dataset[c];
      int i;
      for (i=0; i<int(cinfo->size()); i++)
      {
         char *pbyData = 0;
         wstring file_name = (*cinfo)[i];

         //open file
         ifstream is;
#ifdef _WIN32
         is.open(file_name.c_str(), ios::binary);
#else
         is.open(ws2s(file_name).c_str(), ios::binary);
#endif
         if (is.is_open())
         {
            is.seekg(0, ios::end);
            size_t size = is.tellg();
            pbyData = new char[size];
            is.seekg(0, ios::beg);
            is.read(pbyData, size);
            is.close();

            //read
            ReadTiff(pbyData, val, i);

            //increase
            sl_num++;
         }

         if (pbyData)
            delete []pbyData;
      }

      //create nrrd
      if (val && sl_num == m_slice_num)
      {
         //ok
         data = nrrdNew();
         nrrdWrap(data, val, nrrdTypeUShort, 3, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
         nrrdAxisInfoSet(data, nrrdAxisInfoSpacing, m_xspc, m_yspc, m_zspc);
         nrrdAxisInfoSet(data, nrrdAxisInfoMax, m_xspc*m_x_size, m_yspc*m_y_size, m_zspc*m_slice_num);
         nrrdAxisInfoSet(data, nrrdAxisInfoMin, 0.0, 0.0, 0.0);
         nrrdAxisInfoSet(data, nrrdAxisInfoSize, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
      }
      else
      {
         //something is wrong
         if (val)
            delete []val;
      }
   }

   if (m_max_value > 0.0)
      m_scalar_scale = 65535.0 / m_max_value;

   m_cur_time = t;
   return data;
}
Пример #21
0
	MemoResult Send(const Anope::string &source, const Anope::string &target, const Anope::string &message, bool force)
	{
		bool ischan;
		MemoInfo *mi = this->GetMemoInfo(target, ischan);

		if (mi == NULL)
			return MEMO_INVALID_TARGET;

		User *sender = finduser(source);
		if (sender != NULL && !sender->HasPriv("memoserv/no-limit") && !force)
		{
			if (Config->MSSendDelay > 0 && sender->lastmemosend + Config->MSSendDelay > Anope::CurTime)
				return MEMO_TOO_FAST;
			else if (!mi->memomax)
				return MEMO_TARGET_FULL;
			else if (mi->memomax > 0 && mi->memos.size() >= mi->memomax)
				return MEMO_TARGET_FULL;
			else if (mi->HasIgnore(sender))
				return MEMO_SUCCESS;
		}

		if (sender != NULL)
			sender->lastmemosend = Anope::CurTime;

		Memo *m = new Memo();
		mi->memos.push_back(m);
		m->owner = target;
		m->sender = source;
		m->time = Anope::CurTime;
		m->text = message;
		m->SetFlag(MF_UNREAD);

		FOREACH_MOD(I_OnMemoSend, OnMemoSend(source, target, mi, m));

		if (ischan)
		{
			ChannelInfo *ci = cs_findchan(target);

			if (ci->c)
			{
				for (CUserList::iterator it = ci->c->users.begin(), it_end = ci->c->users.end(); it != it_end; ++it)
				{
					UserContainer *cu = *it;

					if (ci->AccessFor(cu->user).HasPriv("MEMO"))
					{
						if (cu->user->Account() && cu->user->Account()->HasFlag(NI_MEMO_RECEIVE))
							cu->user->SendMessage(MemoServ, MEMO_NEW_X_MEMO_ARRIVED, ci->name.c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), ci->name.c_str(), mi->memos.size());
					}
				}
			}
		}
		else
		{
			NickCore *nc = findnick(target)->nc;

			if (nc->HasFlag(NI_MEMO_RECEIVE))
			{
				for (std::list<NickAlias *>::iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end; ++it)
				{
					NickAlias *na = *it;
					User *user = finduser(na->nick);
					if (user && user->IsIdentified())
						user->SendMessage(MemoServ, MEMO_NEW_MEMO_ARRIVED, source.c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), mi->memos.size());
				}
			}

			/* let's get out the mail if set in the nickcore - certus */
			if (nc->HasFlag(NI_MEMO_MAIL))
				SendMemoMail(nc, mi, m);
		}

		return MEMO_SUCCESS;
	}
Пример #22
0
	void OnDelCore(NickCore *nc)
	{
		// XXX this is slightly inefficient
		for (registered_channel_map::const_iterator it = RegisteredChannelList.begin(), it_end = RegisteredChannelList.end(); it != it_end;)
		{
			ChannelInfo *ci = it->second;
			++it;

			if (ci->GetFounder() == nc)
			{
				NickCore *newowner = NULL;
				if (ci->successor && (ci->successor->IsServicesOper() || !Config->CSMaxReg || ci->successor->channelcount < Config->CSMaxReg))
					newowner = ci->successor;
				else
				{
					ChanAccess *highest = NULL;
					for (unsigned j = 0; j < ci->GetAccessCount(); ++j)
					{
						ChanAccess *ca = ci->GetAccess(j);
						NickCore *anc = findcore(ca->mask);

						if (!anc || (!anc->IsServicesOper() && Config->CSMaxReg && anc->channelcount >= Config->CSMaxReg) || (anc == nc))
							continue;
						if (!highest || *ca > *highest)
							highest = ca;
					}
					if (highest)
						newowner = findcore(highest->mask);
				}

				if (newowner)
				{
					Log(LOG_NORMAL, "chanserv/expire") << "Transferring foundership of " << ci->name << " from deleted nick " << nc->display << " to " << newowner->display;
					ci->SetFounder(newowner);
					ci->successor = NULL;
				}
				else
				{
					Log(LOG_NORMAL, "chanserv/expire") << "Deleting channel " << ci->name << " owned by deleted nick " << nc->display;

					delete ci;
					continue;
				}
			}

			if (ci->successor == nc)
				ci->successor = NULL;

			for (unsigned j = 0; j < ci->GetAccessCount(); ++j)
			{
				ChanAccess *ca = ci->GetAccess(j);
				NickCore *anc = findcore(ca->mask);

				if (anc && anc == nc)
				{
					ci->EraseAccess(j);
					break;
				}
			}

			for (unsigned j = ci->GetAkickCount(); j > 0; --j)
			{
				AutoKick *akick = ci->GetAkick(j - 1);
				if (akick->HasFlag(AK_ISNICK) && akick->nc == nc)
					ci->EraseAkick(j - 1);
			}
		}
	}
Пример #23
0
bool WebCPanel::MemoServ::Memos::OnRequest(HTTPProvider *server, const Anope::string &page_name, HTTPClient *client, HTTPMessage &message, HTTPReply &reply, NickAlias *na, TemplateFileServer::Replacements &replacements)
{
	const Anope::string &chname = message.get_data["channel"];
	ChannelInfo *ci;
	const MemoInfo *mi;
	Memo *m;

	for (registered_channel_map::const_iterator it = RegisteredChannelList->begin(), it_end = RegisteredChannelList->end(); it != it_end; ++it)
	{
		ci = it->second;

		if (ci->AccessFor(na->nc).HasPriv("MEMO"))
		{
			replacements["CHANNEL_NAMES"] = ci->name;
			replacements["ESCAPED_CHANNEL_NAMES"] = HTTPUtils::URLEncode(ci->name);
		}
	}

	if (chname.empty())
	{
		replacements["MESSAGES"] = "No Channel specified, displaying the memos for your Nick";
		mi = &na->nc->memos;
	}
	else
	{
		ci = ChannelInfo::Find(chname);
		if (ci)
		{
			replacements["MESSAGES"] = "Displaying the memos for " + chname + ".";
			mi = &ci->memos;
		}
		else
		{
			replacements["MESSAGES"] = "Channel " + chname + " not found, displaying the memos for your nick";
			mi = &na->nc->memos;
		}

		replacements["CHANNEL_NAME"] = ci->name;
		replacements["ESCAPED_CHANNEL_NAME"] = HTTPUtils::URLEncode(ci->name);
	}
	if (message.post_data.count("receiver") > 0 && message.post_data.count("message") > 0)
	{
		std::vector<Anope::string> params;
		params.push_back(HTTPUtils::URLDecode(message.post_data["receiver"]));
		params.push_back(HTTPUtils::URLDecode(message.post_data["message"]));

		WebPanel::RunCommand(na->nc->display, na->nc, "MemoServ", "memoserv/send", params, replacements, "CMDR");
	}
	if (message.get_data.count("del") > 0 && message.get_data.count("number") > 0)
	{
		std::vector<Anope::string> params;
		if (!chname.empty())
			params.push_back(chname);
		params.push_back(message.get_data["number"]);

		WebPanel::RunCommand(na->nc->display, na->nc, "MemoServ", "memoserv/del", params, replacements, "CMDR");
	}
	if (message.get_data.count("read") > 0 && message.get_data.count("number") > 0)
	{
		std::vector<Anope::string> params;
		int number = -1;

		try
		{
			number = convertTo<int>(message.get_data["number"]);
		}
		catch (const ConvertException &ex)
		{
			replacements["MESSAGES"] = "ERROR - invalid parameter for NUMBER";
		}

		if (number > 0)
		{
			m = mi->GetMemo(number-1);

			if (!m)
				replacements["MESSAGES"] = "ERROR - invalid memo number.";
			else if (message.get_data["read"] == "1")
				m->unread = false;
			else if (message.get_data["read"] == "2")
				m->unread = true;
		}
	}

	for (unsigned i = 0; i < mi->memos->size(); ++i)
	{
		m = mi->GetMemo(i);
		replacements["NUMBER"] = stringify(i+1);
		replacements["SENDER"] = m->sender;
		replacements["TIME"] = Anope::strftime(m->time);
		replacements["TEXT"] = HTTPUtils::Escape(m->text);
		if (m->unread)
			replacements["UNREAD"] = "YES";
		else
			replacements["UNREAD"] = "NO";
	}

	TemplateFileServer page("memoserv/memos.html");
	page.Serve(server, page_name, client, message, reply, replacements);
	return true;
}
Пример #24
0
Nrrd* LSMReader::Convert(int t, int c, bool get_max)
{
    Nrrd *data = 0;
    FILE* pfile = 0;
    if (!WFOPEN(&pfile, m_path_name.c_str(), L"rb"))
        return 0;

    int i, j;

    if (t>=0 && t<m_time_num &&
            c>=0 && c<m_chan_num &&
            m_slice_num > 0 &&
            m_x_size > 0 &&
            m_y_size > 0 &&
            t<(int)m_lsm_info.size() &&
            c<(int)m_lsm_info[t].size())
    {
        //allocate memory for nrrd
        switch (m_datatype)
        {
        case 1://8-bit
        {
            unsigned long long mem_size = (unsigned long long)m_x_size*
                                          (unsigned long long)m_y_size*(unsigned long long)m_slice_num;
            unsigned char *val = new (std::nothrow) unsigned char[mem_size];
            ChannelInfo *cinfo = &m_lsm_info[t][c];
            for (i=0; i<(int)cinfo->size(); i++)
            {
                if (m_l4gb?
                        FSEEK64(pfile, ((uint64_t((*cinfo)[i].offset_high))<<32)+(*cinfo)[i].offset, SEEK_SET)==0:
                        fseek(pfile, (*cinfo)[i].offset, SEEK_SET)==0)
                {
                    unsigned int val_pos = m_x_size*m_y_size*i;
                    if (m_compression==1)
                        fread(val+val_pos, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                    else if (m_compression==5)
                    {
                        unsigned char* tif = new (std::nothrow) unsigned char[(*cinfo)[i].size];
                        fread(tif, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                        LZWDecode(tif, val+val_pos, (*cinfo)[i].size);
                        for (j=0; j<m_y_size; j++)
                            DecodeAcc8(val+val_pos+j*m_x_size, m_x_size,1);
                        delete []tif;
                    }
                }
            }
            //create nrrd
            data = nrrdNew();
            nrrdWrap(data, val, nrrdTypeUChar, 3, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoSpacing, m_xspc, m_yspc, m_zspc);
            nrrdAxisInfoSet(data, nrrdAxisInfoMax, m_xspc*m_x_size, m_yspc*m_y_size, m_zspc*m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoMin, 0.0, 0.0, 0.0);
            nrrdAxisInfoSet(data, nrrdAxisInfoSize, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
        }
        break;
        case 2://16-bit
        case 3:
        {
            unsigned long long mem_size = (unsigned long long)m_x_size*
                                          (unsigned long long)m_y_size*(unsigned long long)m_slice_num;
            unsigned short *val = new (std::nothrow) unsigned short[mem_size];
            ChannelInfo *cinfo = &m_lsm_info[t][c];
            for (i=0; i<(int)cinfo->size(); i++)
            {
                if (m_l4gb?
                        FSEEK64(pfile, ((uint64_t((*cinfo)[i].offset_high))<<32)+(*cinfo)[i].offset, SEEK_SET)==0:
                        fseek(pfile, (*cinfo)[i].offset, SEEK_SET)==0)
                {
                    unsigned int val_pos = m_x_size*m_y_size*i;
                    if (m_compression==1)
                        fread(val+val_pos, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                    else if (m_compression==5)
                    {
                        unsigned char* tif = new (std::nothrow) unsigned char[(*cinfo)[i].size];
                        fread(tif, sizeof(unsigned char), (*cinfo)[i].size, pfile);
                        LZWDecode(tif, (tidata_t)(val+val_pos), (*cinfo)[i].size);
                        for (j=0; j<m_y_size; j++)
                            DecodeAcc16((tidata_t)(val+val_pos+j*m_x_size), m_x_size,1);
                        delete []tif;
                    }
                }
            }
            //create nrrd
            data = nrrdNew();
            nrrdWrap(data, val, nrrdTypeUShort, 3, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoSpacing, m_xspc, m_yspc, m_zspc);
            nrrdAxisInfoSet(data, nrrdAxisInfoMax, m_xspc*m_x_size, m_yspc*m_y_size, m_zspc*m_slice_num);
            nrrdAxisInfoSet(data, nrrdAxisInfoMin, 0.0, 0.0, 0.0);
            nrrdAxisInfoSet(data, nrrdAxisInfoSize, (size_t)m_x_size, (size_t)m_y_size, (size_t)m_slice_num);
        }
        break;
        }
    }

    fclose(pfile);

    return data;
}
Пример #25
0
Nrrd *OIBReader::Convert(int t, int c, bool get_max)
{
   Nrrd *data = 0;
   int sl_num = 0;
   if (t>=0 && t<m_time_num &&
         c>=0 && c<m_chan_num &&
         m_slice_num > 0 &&
         m_x_size > 0 &&
         m_y_size > 0)
   {
	   unsigned char *pbyData = 0;
       wstring path_name = m_type==0?m_path_name:m_oib_info[t].filename;
	   //storage
	   POLE::Storage pStg(ws2s(path_name).c_str()); 
	   //open
	   if (pStg.open()) {
		  //allocate memory for nrrd
		  unsigned long long mem_size = (unsigned long long)m_x_size*
			  (unsigned long long)m_y_size*(unsigned long long)m_slice_num;
		  unsigned short *val = new (std::nothrow) unsigned short[mem_size];
		  //enumerate
		  std::list<std::string> entries = 
			  pStg.entries();
		  for(std::list<std::string>::iterator it = entries.begin();
			  it != entries.end(); ++it) {
			if (pStg.isDirectory(*it)) {
				std::list<std::string> streams =  pStg.GetAllStreams(*it);
				size_t num = 0;
				ChannelInfo *cinfo = &m_oib_info[t].dataset[c];
				for(std::list<std::string>::iterator its = streams.begin();
						its != streams.end(); ++its) {
					if (num >= cinfo->size()) break;
					//fix the stream name
					std::string str_name = ws2s((*cinfo)[num].stream_name);
					std::string name = (*it) + std::string("/") + str_name;
					  
					POLE::Stream pStm(&pStg,name);

					//open
					if (!pStm.eof() && !pStm.fail())
					{
						//get stream size
						size_t sz = pStm.size();
						//allocate 
						pbyData = new unsigned char[sz];
						if (!pbyData) 
							return NULL;
						//read
						if (pStm.read(pbyData,sz)) {
									
							//copy tiff to val
							ReadTiff(pbyData, val, num);

							//increase
							sl_num++;
						}
					}

					//release
					if (pbyData)
						delete[] pbyData;
					num++;
				 }
			  }
		   }

			//create nrrd
			if (val && sl_num == m_slice_num)
			{
				//ok
				data = nrrdNew();
				nrrdWrap(data, val, nrrdTypeUShort, 3, (size_t)m_x_size, (size_t)m_y_size, 
					(size_t)m_slice_num);
				nrrdAxisInfoSet(data, nrrdAxisInfoSpacing, m_xspc, m_yspc, m_zspc);
				nrrdAxisInfoSet(data, nrrdAxisInfoMax, m_xspc*m_x_size, m_yspc*m_y_size, 
					m_zspc*m_slice_num);
				nrrdAxisInfoSet(data, nrrdAxisInfoMin, 0.0, 0.0, 0.0);
				nrrdAxisInfoSet(data, nrrdAxisInfoSize, (size_t)m_x_size,
					(size_t)m_y_size, (size_t)m_slice_num);
			} else {
				//something is wrong
				if (val)
					delete []val;
			}
			//release
			pStg.close();
	  }
    }

	if (m_max_value > 0.0)
		m_scalar_scale = 65535.0 / m_max_value;

	m_cur_time = t;
	return data;
}
Пример #26
0
/*static*/ already_AddRefed<Response>
Response::Constructor(const GlobalObject& aGlobal,
                      const Optional<ArrayBufferOrArrayBufferViewOrBlobOrFormDataOrUSVStringOrURLSearchParams>& aBody,
                      const ResponseInit& aInit, ErrorResult& aRv)
{
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());

  if (aInit.mStatus < 200 || aInit.mStatus > 599) {
    aRv.ThrowRangeError(MSG_INVALID_RESPONSE_STATUSCODE_ERROR);
    return nullptr;
  }

  nsCString statusText;
  if (aInit.mStatusText.WasPassed()) {
    statusText = aInit.mStatusText.Value();
    nsACString::const_iterator start, end;
    statusText.BeginReading(start);
    statusText.EndReading(end);
    if (FindCharInReadable('\r', start, end)) {
      aRv.ThrowTypeError(MSG_RESPONSE_INVALID_STATUSTEXT_ERROR);
      return nullptr;
    }
    // Reset iterator since FindCharInReadable advances it.
    statusText.BeginReading(start);
    if (FindCharInReadable('\n', start, end)) {
      aRv.ThrowTypeError(MSG_RESPONSE_INVALID_STATUSTEXT_ERROR);
      return nullptr;
    }
  } else {
    // Since we don't support default values for ByteString.
    statusText = NS_LITERAL_CSTRING("OK");
  }

  nsRefPtr<InternalResponse> internalResponse =
    new InternalResponse(aInit.mStatus, statusText);

  // Grab a valid channel info from the global so this response is 'valid' for
  // interception.
  if (NS_IsMainThread()) {
    ChannelInfo info;
    nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(global);
    if (window) {
      nsIDocument* doc = window->GetExtantDoc();
      MOZ_ASSERT(doc);
      info.InitFromDocument(doc);
    } else {
      info.InitFromChromeGlobal(global);
    }
    internalResponse->InitChannelInfo(info);
  } else {
    workers::WorkerPrivate* worker = workers::GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(worker);
    internalResponse->InitChannelInfo(worker->GetChannelInfo());
  }

  nsRefPtr<Response> r = new Response(global, internalResponse);

  if (aInit.mHeaders.WasPassed()) {
    internalResponse->Headers()->Clear();

    // Instead of using Fill, create an object to allow the constructor to
    // unwrap the HeadersInit.
    nsRefPtr<Headers> headers =
      Headers::Create(global, aInit.mHeaders.Value(), aRv);
    if (aRv.Failed()) {
      return nullptr;
    }

    internalResponse->Headers()->Fill(*headers->GetInternalHeaders(), aRv);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  }

  if (aBody.WasPassed()) {
    nsCOMPtr<nsIInputStream> bodyStream;
    nsCString contentType;
    aRv = ExtractByteStreamFromBody(aBody.Value(), getter_AddRefs(bodyStream), contentType);
    internalResponse->SetBody(bodyStream);

    if (!contentType.IsVoid() &&
        !internalResponse->Headers()->Has(NS_LITERAL_CSTRING("Content-Type"), aRv)) {
      internalResponse->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), contentType, aRv);
    }

    if (aRv.Failed()) {
      return nullptr;
    }
  }

  r->SetMimeType();
  return r.forget();
}
Пример #27
0
	void Execute(CommandSource &source, const std::vector<Anope::string> &params)
	{
		const Anope::string &channel = params[0];
		const Anope::string &target = params[1];
		Anope::string what = params.size() > 2 ? params[2] : "";

		User *u = source.u;
		ChannelInfo *ci = cs_findchan(params[0]);
		if (ci == NULL)
		{
			source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str());
			return;
		}

		if (!ci->AccessFor(u).HasPriv("SET"))
		{
			source.Reply(ACCESS_DENIED);
			return;
		}
		ChannelInfo *target_ci = cs_findchan(target);
		if (!target_ci)
		{
			source.Reply(CHAN_X_NOT_REGISTERED, target.c_str());
			return;
		}
		if (!IsFounder(u, ci) || !IsFounder(u, target_ci))
		{
			source.Reply(ACCESS_DENIED);
			return;
		}

		if (what.equals_ci("ALL"))
			what.clear();

		if (what.empty())
		{
			delete target_ci;
			target_ci = new ChannelInfo(*ci);
			target_ci->name = target;
			RegisteredChannelList[target_ci->name] = target_ci;
			target_ci->c = findchan(target_ci->name);
			if (target_ci->c)
			{
				target_ci->c->ci = target_ci;

				check_modes(target_ci->c);

				ChannelMode *cm;
				if (u->FindChannel(target_ci->c) != NULL)
				{
					/* On most ircds you do not receive the admin/owner mode till its registered */
					if ((cm = ModeManager::FindChannelModeByName(CMODE_OWNER)))
						target_ci->c->SetMode(NULL, cm, u->nick);
					else if ((cm = ModeManager::FindChannelModeByName(CMODE_PROTECT)))
						target_ci->c->RemoveMode(NULL, cm, u->nick);
				}

				/* Mark the channel as persistent */
				if (target_ci->c->HasMode(CMODE_PERM))
					target_ci->SetFlag(CI_PERSIST);
				/* Persist may be in def cflags, set it here */
				else if (target_ci->HasFlag(CI_PERSIST) && (cm = ModeManager::FindChannelModeByName(CMODE_PERM)))
					target_ci->c->SetMode(NULL, CMODE_PERM);
	
				if (target_ci->bi && target_ci->c->FindUser(target_ci->bi) == NULL)
					target_ci->bi->Join(target_ci->c, &Config->BotModeList);
			}

			if (target_ci->c && !target_ci->c->topic.empty())
			{
				target_ci->last_topic = target_ci->c->topic;
				target_ci->last_topic_setter = target_ci->c->topic_setter;
				target_ci->last_topic_time = target_ci->c->topic_time;
			}
			else
				target_ci->last_topic_setter = source.owner->nick;

			FOREACH_MOD(I_OnChanRegistered, OnChanRegistered(target_ci));

			source.Reply(_("All settings from \002%s\002 have been cloned to \002%s\002"), channel.c_str(), target.c_str());
		}
		else if (what.equals_ci("ACCESS"))
		{
			for (unsigned i = 0; i < ci->GetAccessCount(); ++i)
			{
				ChanAccess *taccess = ci->GetAccess(i);
				AccessProvider *provider = taccess->provider;

				ChanAccess *newaccess = provider->Create();
				newaccess->ci = target_ci;
				newaccess->mask = taccess->mask;
				newaccess->creator = taccess->creator;
				newaccess->last_seen = taccess->last_seen;
				newaccess->created = taccess->created;
				newaccess->Unserialize(taccess->Serialize());

				target_ci->AddAccess(newaccess);
			}

			source.Reply(_("All access entries from \002%s\002 have been cloned to \002%s\002"), channel.c_str(), target.c_str());
		}
		else if (what.equals_ci("AKICK"))
		{
			target_ci->ClearAkick();
			for (unsigned i = 0; i < ci->GetAkickCount(); ++i)
			{
				AutoKick *akick = ci->GetAkick(i);
				if (akick->HasFlag(AK_ISNICK))
					target_ci->AddAkick(akick->creator, akick->nc, akick->reason, akick->addtime, akick->last_used);
				else
					target_ci->AddAkick(akick->creator, akick->mask, akick->reason, akick->addtime, akick->last_used);
			}

			source.Reply(_("All akick entries from \002%s\002 have been cloned to \002%s\002"), channel.c_str(), target.c_str());
		}
		else if (what.equals_ci("BADWORDS"))
		{
			target_ci->ClearBadWords();
			for (unsigned i = 0; i < ci->GetBadWordCount(); ++i)
			{
				BadWord *bw = ci->GetBadWord(i);
				target_ci->AddBadWord(bw->word, bw->type);
			}

			source.Reply(_("All badword entries from \002%s\002 have been cloned to \002%s\002"), channel.c_str(), target.c_str());
		}
		else
		{
			this->OnSyntaxError(source, "");
			return;
		}

		Log(LOG_COMMAND, u, this, ci) << "to clone " << (what.empty() ? "everything from it" : what) << " to " << target_ci->name;

		return;
	}