2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- Copyright (C) 2014 Daurnimator
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
10 local select = select;
11 local pairs, ipairs = pairs, ipairs;
13 local setmetatable = setmetatable;
15 local dataform = require "util.dataforms";
16 local iterators = require "util.iterators";
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local jid_join = require "util.jid".join;
21 local st = require "util.stanza";
22 local log = require "util.logger".init("mod_muc");
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
26 local occupant_lib = module:require "muc/occupant"
27 local muc_util = module:require "muc/util";
28 local is_kickable_error = muc_util.is_kickable_error;
29 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
32 room_mt.__index = room_mt;
34 function room_mt:__tostring()
35 return "MUC room ("..self.jid..")";
38 function room_mt:get_occupant_jid(real_jid)
39 return self._jid_nick[real_jid]
42 function room_mt:get_default_role(affiliation)
43 local role = module:fire_event("muc-get-default-role", {
45 affiliation = affiliation;
46 affiliation_rank = valid_affiliations[affiliation or "none"];
48 return role, valid_roles[role or "none"];
50 module:hook("muc-get-default-role", function(event)
51 if event.affiliation_rank >= valid_affiliations.admin then
53 elseif event.affiliation_rank >= valid_affiliations.none then
58 --- Occupant functions
59 function room_mt:new_occupant(bare_real_jid, nick)
60 local occupant = occupant_lib.new(bare_real_jid, nick);
61 local affiliation = self:get_affiliation(bare_real_jid);
62 occupant.role = self:get_default_role(affiliation);
66 function room_mt:get_occupant_by_nick(nick)
67 local occupant = self._occupants[nick];
68 if occupant == nil then return nil end
69 return occupant_lib.copy(occupant);
73 local function next_copied_occupant(occupants, occupant_jid)
74 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
75 if next_occupant_jid == nil then return nil end
76 return next_occupant_jid, occupant_lib.copy(raw_occupant);
78 function room_mt:each_occupant(read_only)
79 return next_copied_occupant, self._occupants, nil;
83 function room_mt:has_occupant()
84 return next(self._occupants, nil) ~= nil
87 function room_mt:get_occupant_by_real_jid(real_jid)
88 local occupant_jid = self:get_occupant_jid(real_jid);
89 if occupant_jid == nil then return nil end
90 return self:get_occupant_by_nick(occupant_jid);
93 function room_mt:save_occupant(occupant)
94 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
95 local id = occupant.nick
97 -- Need to maintain _jid_nick secondary index
98 local old_occupant = self._occupants[id];
100 for real_jid in old_occupant:each_session() do
101 self._jid_nick[real_jid] = nil;
105 local has_live_session = false
106 if occupant.role ~= nil then
107 for real_jid, presence in occupant:each_session() do
108 if presence.attr.type == nil then
109 has_live_session = true
110 self._jid_nick[real_jid] = occupant.nick;
113 if not has_live_session then
114 -- Has no live sessions left; they have left the room.
118 if not has_live_session then
121 self._occupants[id] = occupant
124 function room_mt:route_to_occupant(occupant, stanza)
125 local to = stanza.attr.to;
126 for jid, pr in occupant:each_session() do
127 stanza.attr.to = jid;
128 self:route_stanza(stanza);
133 -- actor is the attribute table
134 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
135 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
136 if actor_nick or actor_jid then
137 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
140 x:tag("reason"):text(reason):up()
146 -- actor is (real) jid
147 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
148 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
149 local role = occupant.role or "none";
151 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
153 for real_jid, session in occupant:each_session() do
154 add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
160 function room_mt:broadcast_message(stanza)
161 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
164 self:broadcast(stanza);
168 -- Broadcast a stanza to all occupants in the room.
169 -- optionally checks conditional called with (nick, occupant)
170 function room_mt:broadcast(stanza, cond_func)
171 for nick, occupant in self:each_occupant() do
172 if cond_func == nil or cond_func(nick, occupant) then
173 self:route_to_occupant(occupant, stanza)
178 local function can_see_real_jids(whois, occupant)
179 if whois == "anyone" then
181 elseif whois == "moderators" then
182 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
186 -- Broadcasts an occupant's presence to the whole room
187 -- Takes the x element that goes into the stanzas
188 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
189 -- Build real jid and (optionally) occupant jid template presences
191 if occupant.role ~= nil then
192 -- Try to use main jid's presence
193 local pr = occupant:get_presence();
195 base_presence = st.clone(pr);
198 base_presence = base_presence or st.presence {from = occupant.nick; type = "unavailable";};
200 -- Fire event (before full_p and anon_p are created)
201 module:fire_event("muc-broadcast-presence", {
202 room = self; stanza = base_presence; x = base_x;
203 occupant = occupant; nick = nick; actor = actor;
207 local whois = self:get_whois();
210 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
213 local full_p, full_x;
214 local function get_full_p()
215 if full_p == nil then
216 full_x = st.clone(base_x);
217 self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
218 full_p = st.clone(base_presence):add_child(full_x);
220 return full_p, full_x;
223 local anon_p, anon_x;
224 local function get_anon_p()
225 if anon_p == nil then
226 anon_x = st.clone(base_x);
227 self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
228 anon_p = st.clone(base_presence):add_child(anon_x);
230 return anon_p, anon_x;
233 local self_p, self_x;
234 if can_see_real_jids(whois, occupant) then
235 self_p, self_x = get_full_p();
237 -- Can always see your own full jids
238 -- But not allowed to see actor's
239 self_x = st.clone(base_x);
240 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
241 self_p = st.clone(base_presence):add_child(self_x);
245 for nick, n_occupant in self:each_occupant() do
246 if nick ~= occupant.nick then
248 if can_see_real_jids(whois, n_occupant) then
250 elseif occupant.bare_jid == n_occupant.bare_jid then
255 self:route_to_occupant(n_occupant, pr);
259 -- Presences for occupant itself
260 self_x:tag("status", {code = "110";}):up();
261 if occupant.role == nil then
262 -- They get an unavailable
263 self:route_to_occupant(occupant, self_p);
265 -- use their own presences as templates
266 for full_jid, pr in occupant:each_session() do
268 pr.attr.to = full_jid;
269 pr:add_child(self_x);
270 self:route_stanza(pr);
275 function room_mt:send_occupant_list(to, filter)
276 local to_bare = jid_bare(to);
277 local is_anonymous = false;
278 local whois = self:get_whois();
279 if whois ~= "anyone" then
280 local affiliation = self:get_affiliation(to);
281 if affiliation ~= "admin" and affiliation ~= "owner" then
282 local occupant = self:get_occupant_by_real_jid(to);
283 if not (occupant and can_see_real_jids(whois, occupant)) then
288 for occupant_jid, occupant in self:each_occupant() do
289 if filter == nil or filter(occupant_jid, occupant) then
290 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
291 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
292 local pres = st.clone(occupant:get_presence());
295 self:route_stanza(pres);
300 function room_mt:get_disco_info(stanza)
301 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
302 local form = dataform.new {
303 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
305 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
306 reply:add_child(form:form(nil, "result"));
309 module:hook("muc-disco#info", function(event)
310 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
312 module:hook("muc-disco#info", function(event)
313 local count = iterators.count(event.room:each_occupant());
314 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
317 function room_mt:get_disco_items(stanza)
318 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
319 for room_jid in self:each_occupant() do
320 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
325 function room_mt:handle_kickable(origin, stanza)
326 local real_jid = stanza.attr.from;
327 local occupant = self:get_occupant_by_real_jid(real_jid);
328 if occupant == nil then return nil; end
329 local type, condition, text = stanza:get_error();
330 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
332 error_message = error_message..": "..text;
334 occupant:set_session(real_jid, st.presence({type="unavailable"})
335 :tag('status'):text(error_message));
336 self:save_occupant(occupant);
337 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
338 :tag("status", {code = "307"})
339 self:publicise_occupant_status(occupant, x);
340 if occupant.jid == real_jid then -- Was last session
341 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
346 -- Give the room creator owner affiliation
347 module:hook("muc-room-pre-create", function(event)
348 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
351 -- check if user is banned
352 module:hook("muc-occupant-pre-join", function(event)
353 local room, stanza = event.room, event.stanza;
354 local affiliation = room:get_affiliation(stanza.attr.from);
355 if affiliation == "outcast" then
356 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
357 reply.tags[1].attr.code = "403";
358 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
363 function room_mt:handle_presence_to_occupant(origin, stanza)
364 local type = stanza.attr.type;
365 if type == "error" then -- error, kick em out!
366 return self:handle_kickable(origin, stanza)
367 elseif type == nil or type == "unavailable" then
368 local real_jid = stanza.attr.from;
369 local bare_jid = jid_bare(real_jid);
370 local orig_occupant, dest_occupant;
371 local is_new_room = next(self._affiliations) == nil;
373 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
374 if module:fire_event("muc-room-pre-create", {
378 }) then return true; end
380 orig_occupant = self:get_occupant_by_real_jid(real_jid);
381 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
383 local is_first_dest_session;
384 if type == "unavailable" then
385 -- dest_occupant = nil
386 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
387 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
388 dest_occupant = orig_occupant;
390 local dest_jid = stanza.attr.to;
391 dest_occupant = self:get_occupant_by_nick(dest_jid);
392 if dest_occupant == nil then
393 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
394 is_first_dest_session = true;
395 dest_occupant = self:new_occupant(bare_jid, dest_jid);
397 is_first_dest_session = false;
400 local is_last_orig_session;
401 if orig_occupant ~= nil then
402 -- Is there are least 2 sessions?
403 local iter, ob, last = orig_occupant:each_session();
404 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
407 local event, event_name = {
411 is_first_session = is_first_dest_session;
412 is_last_session = is_last_orig_session;
414 if orig_occupant == nil then
415 event_name = "muc-occupant-pre-join";
416 event.is_new_room = is_new_room;
417 event.occupant = dest_occupant;
418 elseif dest_occupant == nil then
419 event_name = "muc-occupant-pre-leave";
420 event.occupant = orig_occupant;
422 event_name = "muc-occupant-pre-change";
423 event.orig_occupant = orig_occupant;
424 event.dest_occupant = dest_occupant;
426 if module:fire_event(event_name, event) then return true; end
428 -- Check for nick conflicts
429 if dest_occupant ~= nil and not is_first_dest_session and bare_jid ~= jid_bare(dest_occupant.bare_jid) then -- new nick or has different bare real jid
430 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
431 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
432 reply.tags[1].attr.code = "409";
433 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
437 -- Send presence stanza about original occupant
438 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
439 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
441 if dest_occupant == nil then -- Session is leaving
442 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
443 if is_last_orig_session then
444 orig_occupant.role = nil;
446 orig_occupant:set_session(real_jid, stanza);
448 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
449 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
450 orig_occupant:set_session(real_jid, generated_unavail);
451 dest_nick = select(3, jid_split(dest_occupant.nick));
452 if not is_first_dest_session then -- User is swapping into another pre-existing session
453 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
454 -- Show the other session leaving
455 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
456 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
457 add_item(x, self:get_affiliation(bare_jid), "none");
458 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
460 self:route_stanza(pr);
462 if is_first_dest_session and is_last_orig_session then -- Normal nick change
463 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
464 orig_x:tag("status", {code = "303";}):up();
465 else -- The session itself always needs to see a nick change
466 -- don't want to get our old nick's available presence,
467 -- so remove our session from there, and manually generate an unavailable
468 orig_occupant:remove_session(real_jid);
469 log("debug", "generating nick change for %s", real_jid);
470 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
471 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
472 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
473 x:tag("status", {code = "303";}):up();
474 x:tag("status", {code = "110";}):up();
475 self:route_stanza(generated_unavail:add_child(x));
476 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
479 self:save_occupant(orig_occupant);
480 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
482 if is_last_orig_session then
483 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
487 if dest_occupant ~= nil then
488 dest_occupant:set_session(real_jid, stanza);
489 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
491 dest_x:tag("status", {code = "201"}):up();
493 if orig_occupant == nil and self:get_whois() == "anyone" then
494 dest_x:tag("status", {code = "100"}):up();
496 self:save_occupant(dest_occupant);
498 if orig_occupant == nil then
499 -- Send occupant list to newly joined user
500 self:send_occupant_list(real_jid, function(nick, occupant)
501 -- Don't include self
502 return occupant:get_presence(real_jid) == nil;
505 self:publicise_occupant_status(dest_occupant, dest_x);
507 if orig_occupant ~= nil and orig_occupant ~= dest_occupant and not is_last_orig_session then -- If user is swapping and wasn't last original session
508 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
509 -- Show the original nick joining again
510 local pr = st.clone(orig_occupant:get_presence());
511 pr.attr.to = real_jid;
512 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
513 self:build_item_list(orig_occupant, x, false);
514 -- TODO: new status code to inform client this was the multi-session it left?
516 self:route_stanza(pr);
519 if orig_occupant == nil then
520 if is_first_dest_session then
521 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
523 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
526 elseif type ~= 'result' then -- bad type
527 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
528 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
534 function room_mt:handle_iq_to_occupant(origin, stanza)
535 local from, to = stanza.attr.from, stanza.attr.to;
536 local type = stanza.attr.type;
537 local id = stanza.attr.id;
538 local occupant = self:get_occupant_by_nick(to);
539 if (type == "error" or type == "result") then
540 do -- deconstruct_stanza_id
541 if not occupant then return nil; end
542 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
543 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
544 local from_occupant_jid = self:get_occupant_jid(from_jid);
545 if from_occupant_jid == nil then return nil; end
547 for to_jid in occupant:each_session() do
548 if md5(to_jid) == to_jid_hash then
549 session_jid = to_jid;
553 if session_jid == nil then return nil; end
554 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, id;
556 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
557 self:route_stanza(stanza);
558 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
560 else -- Type is "get" or "set"
561 local current_nick = self:get_occupant_jid(from);
562 if not current_nick then
563 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
566 if not occupant then -- recipient not in room
567 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
570 do -- construct_stanza_id
571 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
573 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
574 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
575 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
576 stanza.attr.to = jid_bare(stanza.attr.to);
578 self:route_stanza(stanza);
579 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
584 function room_mt:handle_message_to_occupant(origin, stanza)
585 local from, to = stanza.attr.from, stanza.attr.to;
586 local current_nick = self:get_occupant_jid(from);
587 local type = stanza.attr.type;
588 if not current_nick then -- not in room
589 if type ~= "error" then
590 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
594 if type == "groupchat" then -- groupchat messages not allowed in PM
595 origin.send(st.error_reply(stanza, "modify", "bad-request"));
597 elseif type == "error" and is_kickable_error(stanza) then
598 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
599 return self:handle_kickable(origin, stanza); -- send unavailable
602 local o_data = self:get_occupant_by_nick(to);
604 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
607 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
608 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
609 stanza.attr.from = current_nick;
610 self:route_to_occupant(o_data, stanza)
611 -- TODO: Remove x tag?
612 stanza.attr.from = from;
616 function room_mt:send_form(origin, stanza)
617 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
618 :add_child(self:get_form_layout(stanza.attr.from):form())
622 function room_mt:get_form_layout(actor)
623 local form = dataform.new({
624 title = "Configuration for "..self.jid,
625 instructions = "Complete and submit this form to configure the room.",
629 value = 'http://jabber.org/protocol/muc#roomconfig'
632 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
635 function room_mt:process_form(origin, stanza)
636 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
637 if form.attr.type == "cancel" then
638 origin.send(st.reply(stanza));
639 elseif form.attr.type == "submit" then
641 if form.tags[1] == nil then -- Instant room
644 fields = self:get_form_layout(stanza.attr.from):data(form);
645 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
646 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
651 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
652 function event.update_option(name, field, allowed)
653 local new = fields[field];
654 if new == nil then return; end
655 if allowed and not allowed[new] then return; end
656 if new == self["get_"..name](self) then return; end
657 event.status_codes["104"] = true;
658 self["set_"..name](self, new);
661 module:fire_event("muc-config-submitted", event);
663 if self.save then self:save(true); end
664 origin.send(st.reply(stanza));
666 if next(event.status_codes) then
667 local msg = st.message({type='groupchat', from=self.jid})
668 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
669 for code in pairs(event.status_codes) do
670 msg:tag("status", {code = code;}):up();
673 self:broadcast_message(msg);
676 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
681 -- Removes everyone from the room
682 function room_mt:clear(x)
683 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
684 local occupants_updated = {};
685 for nick, occupant in self:each_occupant() do
687 self:save_occupant(occupant);
688 occupants_updated[occupant] = true;
690 for occupant in pairs(occupants_updated) do
691 self:publicise_occupant_status(occupant, x);
692 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
696 function room_mt:destroy(newjid, reason, password)
697 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
698 :tag("item", { affiliation='none', role='none' }):up()
699 :tag("destroy", {jid=newjid});
700 if reason then x:tag("reason"):text(reason):up(); end
701 if password then x:tag("password"):text(password):up(); end
704 module:fire_event("muc-room-destroyed", { room = self });
707 function room_mt:handle_disco_info_get_query(origin, stanza)
708 origin.send(self:get_disco_info(stanza));
712 function room_mt:handle_disco_items_get_query(origin, stanza)
713 origin.send(self:get_disco_items(stanza));
717 function room_mt:handle_admin_query_set_command(origin, stanza)
718 local item = stanza.tags[1].tags[1];
719 if item.attr.jid then -- Validate provided JID
720 item.attr.jid = jid_prep(item.attr.jid);
721 if not item.attr.jid then
722 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
726 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
727 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
728 if occupant then item.attr.jid = occupant.jid; end
729 elseif not item.attr.nick and item.attr.jid then
730 local nick = self:get_occupant_jid(item.attr.jid);
731 if nick then item.attr.nick = select(3, jid_split(nick)); end
733 local actor = stanza.attr.from;
734 local reason = item:get_child_text("reason");
735 local success, errtype, err
736 if item.attr.affiliation and item.attr.jid and not item.attr.role then
737 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
738 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
739 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
741 success, errtype, err = nil, "cancel", "bad-request";
743 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
744 origin.send(st.reply(stanza));
748 function room_mt:handle_admin_query_get_command(origin, stanza)
749 local actor = stanza.attr.from;
750 local affiliation = self:get_affiliation(actor);
751 local item = stanza.tags[1].tags[1];
752 local _aff = item.attr.affiliation;
753 local _aff_rank = valid_affiliations[_aff or "none"];
754 local _rol = item.attr.role;
755 if _aff and _aff_rank and not _rol then
756 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
757 -- e.g. an admin can't ask for a list of owners
758 local affiliation_rank = valid_affiliations[affiliation];
759 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
760 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
761 for jid in self:each_affiliation(_aff or "none") do
762 reply:tag("item", {affiliation = _aff, jid = jid}):up();
764 origin.send(reply:up());
767 origin.send(st.error_reply(stanza, "auth", "forbidden"));
770 elseif _rol and valid_roles[_rol or "none"] and not _aff then
771 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
772 if valid_roles[role or "none"] >= valid_roles.moderator then
773 if _rol == "none" then _rol = nil; end
774 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
775 -- TODO: whois check here? (though fully anonymous rooms are not supported)
776 for occupant_jid, occupant in self:each_occupant() do
777 if occupant.role == _rol then
778 local nick = select(3,jid_split(occupant_jid));
779 self:build_item_list(occupant, reply, false, nick);
782 origin.send(reply:up());
785 origin.send(st.error_reply(stanza, "auth", "forbidden"));
789 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
794 function room_mt:handle_owner_query_get_to_room(origin, stanza)
795 if self:get_affiliation(stanza.attr.from) ~= "owner" then
796 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
800 self:send_form(origin, stanza);
803 function room_mt:handle_owner_query_set_to_room(origin, stanza)
804 if self:get_affiliation(stanza.attr.from) ~= "owner" then
805 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
809 local child = stanza.tags[1].tags[1];
811 origin.send(st.error_reply(stanza, "modify", "bad-request"));
813 elseif child.name == "destroy" then
814 local newjid = child.attr.jid;
815 local reason = child:get_child_text("reason");
816 local password = child:get_child_text("password");
817 self:destroy(newjid, reason, password);
818 origin.send(st.reply(stanza));
820 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
821 return self:process_form(origin, stanza);
823 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
828 function room_mt:handle_groupchat_to_room(origin, stanza)
829 local from = stanza.attr.from;
830 local occupant = self:get_occupant_by_real_jid(from);
831 if module:fire_event("muc-occupant-groupchat", {
832 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
833 }) then return true; end
834 stanza.attr.from = occupant.nick;
835 self:broadcast_message(stanza);
836 stanza.attr.from = from;
841 module:hook("muc-occupant-groupchat", function(event)
842 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
843 if role_rank <= valid_roles.none then
844 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
846 elseif role_rank <= valid_roles.visitor then
847 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
852 -- hack - some buggy clients send presence updates to the room rather than their nick
853 function room_mt:handle_presence_to_room(origin, stanza)
854 local current_nick = self:get_occupant_jid(stanza.attr.from);
857 local to = stanza.attr.to;
858 stanza.attr.to = current_nick;
859 handled = self:handle_presence_to_occupant(origin, stanza);
865 -- Need visitor role or higher to invite
866 module:hook("muc-pre-invite", function(event)
867 local room, stanza = event.room, event.stanza;
868 local _from, _to = stanza.attr.from, stanza.attr.to;
869 local inviter = room:get_occupant_by_real_jid(_from);
870 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
871 if valid_roles[role or "none"] <= valid_roles.visitor then
872 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
877 function room_mt:handle_mediated_invite(origin, stanza)
878 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
879 local invitee = jid_prep(payload.attr.to);
881 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
883 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
886 local invite = muc_util.filter_muc_x(st.clone(stanza));
887 invite.attr.from = self.jid;
888 invite.attr.to = invitee;
889 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
890 :tag('invite', {from = stanza.attr.from;})
891 :tag('reason'):text(payload:get_child_text("reason")):up()
894 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
895 self:route_stanza(invite);
900 -- COMPAT: Some older clients expect this
901 module:hook("muc-invite", function(event)
902 local room, stanza = event.room, event.stanza;
903 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
904 local reason = invite:get_child_text("reason");
905 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
910 -- Add a plain message for clients which don't support invites
911 module:hook("muc-invite", function(event)
912 local room, stanza = event.room, event.stanza;
913 if not stanza:get_child("body") then
914 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
915 local reason = invite:get_child_text("reason") or "";
917 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
922 function room_mt:handle_mediated_decline(origin, stanza)
923 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
924 local declinee = jid_prep(payload.attr.to);
926 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
928 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
931 local decline = muc_util.filter_muc_x(st.clone(stanza));
932 decline.attr.from = self.jid;
933 decline.attr.to = declinee;
934 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
935 :tag("decline", {from = stanza.attr.from})
936 :tag("reason"):text(payload:get_child_text("reason")):up()
939 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
940 local declinee = decline.attr.to; -- re-fetch, in case event modified it
942 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
943 occupant = self:get_occupant_by_nick(declinee);
946 self:route_to_occupant(occupant, decline);
948 self:route_stanza(decline);
954 -- Add a plain message for clients which don't support declines
955 module:hook("muc-decline", function(event)
956 local room, stanza = event.room, event.stanza;
957 if not stanza:get_child("body") then
958 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
959 local reason = decline:get_child_text("reason") or "";
961 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
966 function room_mt:handle_message_to_room(origin, stanza)
967 local type = stanza.attr.type;
968 if type == "groupchat" then
969 return self:handle_groupchat_to_room(origin, stanza)
970 elseif type == "error" and is_kickable_error(stanza) then
971 return self:handle_kickable(origin, stanza)
972 elseif type == nil then
973 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
975 local payload = x.tags[1];
976 if payload == nil then
978 elseif payload.name == "invite" and payload.attr.to then
979 return self:handle_mediated_invite(origin, stanza)
980 elseif payload.name == "decline" and payload.attr.to then
981 return self:handle_mediated_decline(origin, stanza)
983 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
989 function room_mt:route_stanza(stanza)
993 function room_mt:get_affiliation(jid)
994 local node, host, resource = jid_split(jid);
995 local bare = node and node.."@"..host or host;
996 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
997 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1001 -- Iterates over jid, affiliation pairs
1002 function room_mt:each_affiliation(with_affiliation)
1003 if not with_affiliation then
1004 return pairs(self._affiliations);
1006 return function(_affiliations, jid)
1008 repeat -- Iterate until we get a match
1009 jid, affiliation = next(_affiliations, jid);
1010 until jid == nil or affiliation == with_affiliation
1011 return jid, affiliation;
1012 end, self._affiliations, nil
1016 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1017 if not actor then return nil, "modify", "not-acceptable"; end;
1019 local node, host, resource = jid_split(jid);
1020 if not host then return nil, "modify", "not-acceptable"; end
1021 jid = jid_join(node, host); -- Bare
1022 local is_host_only = node == nil;
1024 if valid_affiliations[affiliation or "none"] == nil then
1025 return nil, "modify", "not-acceptable";
1027 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1029 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1030 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1032 if actor == true then
1033 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1035 local actor_affiliation = self:get_affiliation(actor);
1036 if actor_affiliation == "owner" then
1037 if jid_bare(actor) == jid then -- self change
1038 -- need at least one owner
1039 local is_last = true;
1040 for j in self:each_affiliation("owner") do
1041 if j ~= jid then is_last = false; break; end
1044 return nil, "cancel", "conflict";
1047 -- owners can do anything else
1048 elseif affiliation == "owner" or affiliation == "admin"
1049 or actor_affiliation ~= "admin"
1050 or target_affiliation == "owner" or target_affiliation == "admin" then
1051 -- Can't demote owners or other admins
1052 return nil, "cancel", "not-allowed";
1056 -- Set in 'database'
1057 self._affiliations[jid] = affiliation;
1060 local role = self:get_default_role(affiliation);
1061 local role_rank = valid_roles[role or "none"];
1062 local occupants_updated = {}; -- Filled with old roles
1063 for nick, occupant in self:each_occupant() do
1064 if occupant.bare_jid == jid or (
1065 -- Outcast can be by host.
1066 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1068 -- need to publcize in all cases; as affiliation in <item/> has changed.
1069 occupants_updated[occupant] = occupant.role;
1070 if occupant.role ~= role and (
1072 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1074 occupant.role = role;
1075 self:save_occupant(occupant);
1080 -- Tell the room of the new occupant affiliations+roles
1081 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1082 if not role then -- getting kicked
1083 if affiliation == "outcast" then
1084 x:tag("status", {code="301"}):up(); -- banned
1086 x:tag("status", {code="321"}):up(); -- affiliation change
1089 local is_semi_anonymous = self:get_whois() == "moderators";
1090 for occupant, old_role in pairs(occupants_updated) do
1091 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1092 if occupant.role == nil then
1093 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1094 elseif is_semi_anonymous and
1095 (old_role == "moderator" and occupant.role ~= "moderator") or
1096 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1097 -- Send everyone else's presences (as jid visibility has changed)
1098 for real_jid in occupant:each_session() do
1099 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1100 return occupant.bare_jid ~= jid;
1106 if self.save then self:save(); end
1108 module:fire_event("muc-set-affiliation", {
1112 affiliation = affiliation or "none";
1114 previous_affiliation = target_affiliation;
1115 in_room = next(occupants_updated) ~= nil;
1121 function room_mt:get_role(nick)
1122 local occupant = self:get_occupant_by_nick(nick);
1123 return occupant and occupant.role or nil;
1126 function room_mt:set_role(actor, occupant_jid, role, reason)
1127 if not actor then return nil, "modify", "not-acceptable"; end
1129 local occupant = self:get_occupant_by_nick(occupant_jid);
1130 if not occupant then return nil, "modify", "not-acceptable"; end
1132 if valid_roles[role or "none"] == nil then
1133 return nil, "modify", "not-acceptable";
1135 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1137 if actor == true then
1138 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1140 -- Can't do anything to other owners or admins
1141 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1142 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1143 return nil, "cancel", "not-allowed";
1146 -- If you are trying to give or take moderator role you need to be an owner or admin
1147 if occupant.role == "moderator" or role == "moderator" then
1148 local actor_affiliation = self:get_affiliation(actor);
1149 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1150 return nil, "cancel", "not-allowed";
1154 -- Need to be in the room and a moderator
1155 local actor_occupant = self:get_occupant_by_real_jid(actor);
1156 if not actor_occupant or actor_occupant.role ~= "moderator" then
1157 return nil, "cancel", "not-allowed";
1161 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1163 x:tag("status", {code = "307"}):up();
1165 occupant.role = role;
1166 self:save_occupant(occupant);
1167 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1169 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1174 local affiliation_notify = module:require "muc/affiliation_notify";
1176 local name = module:require "muc/name";
1177 room_mt.get_name = name.get;
1178 room_mt.set_name = name.set;
1180 local description = module:require "muc/description";
1181 room_mt.get_description = description.get;
1182 room_mt.set_description = description.set;
1184 local hidden = module:require "muc/hidden";
1185 room_mt.get_hidden = hidden.get;
1186 room_mt.set_hidden = hidden.set;
1187 function room_mt:get_public()
1188 return not self:get_hidden();
1190 function room_mt:set_public(public)
1191 return self:set_hidden(not public);
1194 local password = module:require "muc/password";
1195 room_mt.get_password = password.get;
1196 room_mt.set_password = password.set;
1198 local whois = module:require "muc/whois";
1199 room_mt.get_whois = whois.get;
1200 room_mt.set_whois = whois.set;
1202 local members_only = module:require "muc/members_only";
1203 room_mt.get_members_only = members_only.get;
1204 room_mt.set_members_only = members_only.set;
1206 local moderated = module:require "muc/moderated";
1207 room_mt.get_moderated = moderated.get;
1208 room_mt.set_moderated = moderated.set;
1210 local persistent = module:require "muc/persistent";
1211 room_mt.get_persistent = persistent.get;
1212 room_mt.set_persistent = persistent.set;
1214 local subject = module:require "muc/subject";
1215 room_mt.get_changesubject = subject.get_changesubject;
1216 room_mt.set_changesubject = subject.set_changesubject;
1217 room_mt.get_subject = subject.get;
1218 room_mt.set_subject = subject.set;
1219 room_mt.send_subject = subject.send;
1221 local history = module:require "muc/history";
1222 room_mt.send_history = history.send;
1223 room_mt.get_historylength = history.get_length;
1224 room_mt.set_historylength = history.set_length;
1226 local _M = {}; -- module "muc"
1228 function _M.new_room(jid, config)
1229 return setmetatable({
1239 _M.room_mt = room_mt;