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;
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 -- FIXME Explain what 'read_only' is supposed to be
79 function room_mt:each_occupant(read_only) -- luacheck: ignore 212
80 return next_copied_occupant, self._occupants, nil;
84 function room_mt:has_occupant()
85 return next(self._occupants, nil) ~= nil
88 function room_mt:get_occupant_by_real_jid(real_jid)
89 local occupant_jid = self:get_occupant_jid(real_jid);
90 if occupant_jid == nil then return nil end
91 return self:get_occupant_by_nick(occupant_jid);
94 function room_mt:save_occupant(occupant)
95 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
96 local id = occupant.nick
98 -- Need to maintain _jid_nick secondary index
99 local old_occupant = self._occupants[id];
101 for real_jid in old_occupant:each_session() do
102 self._jid_nick[real_jid] = nil;
106 local has_live_session = false
107 if occupant.role ~= nil then
108 for real_jid, presence in occupant:each_session() do
109 if presence.attr.type == nil then
110 has_live_session = true
111 self._jid_nick[real_jid] = occupant.nick;
114 if not has_live_session then
115 -- Has no live sessions left; they have left the room.
119 if not has_live_session then
122 self._occupants[id] = occupant
125 function room_mt:route_to_occupant(occupant, stanza)
126 local to = stanza.attr.to;
127 for jid in occupant:each_session() do
128 stanza.attr.to = jid;
129 self:route_stanza(stanza);
134 -- actor is the attribute table
135 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
136 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
137 if actor_nick or actor_jid then
138 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
141 x:tag("reason"):text(reason):up()
147 -- actor is (real) jid
148 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
149 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
150 local role = occupant.role or "none";
152 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
154 for real_jid in occupant:each_session() do
155 add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
161 function room_mt:broadcast_message(stanza)
162 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
165 self:broadcast(stanza);
169 -- Broadcast a stanza to all occupants in the room.
170 -- optionally checks conditional called with (nick, occupant)
171 function room_mt:broadcast(stanza, cond_func)
172 for nick, occupant in self:each_occupant() do
173 if cond_func == nil or cond_func(nick, occupant) then
174 self:route_to_occupant(occupant, stanza)
179 local function can_see_real_jids(whois, occupant)
180 if whois == "anyone" then
182 elseif whois == "moderators" then
183 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
187 -- Broadcasts an occupant's presence to the whole room
188 -- Takes the x element that goes into the stanzas
189 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
190 -- Build real jid and (optionally) occupant jid template presences
191 local base_presence do
192 -- Try to use main jid's presence
193 local pr = occupant:get_presence();
194 if pr and (pr.attr.type ~= "unavailable" or occupant.role == nil) then
195 base_presence = st.clone(pr);
196 else -- user is leaving but didn't send a leave presence. make one for them
197 base_presence = st.presence {from = occupant.nick; type = "unavailable";};
201 -- Fire event (before full_p and anon_p are created)
203 room = self; stanza = base_presence; x = base_x;
204 occupant = occupant; nick = nick; actor = actor;
207 module:fire_event("muc-broadcast-presence", event);
209 -- Allow muc-broadcast-presence listeners to change things
212 reason = event.reason;
214 local whois = self:get_whois();
218 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
221 local full_p, full_x;
222 local function get_full_p()
223 if full_p == nil then
224 full_x = st.clone(base_x);
225 self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
226 full_p = st.clone(base_presence):add_child(full_x);
228 return full_p, full_x;
231 local anon_p, anon_x;
232 local function get_anon_p()
233 if anon_p == nil then
234 anon_x = st.clone(base_x);
235 self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
236 anon_p = st.clone(base_presence):add_child(anon_x);
238 return anon_p, anon_x;
241 local self_p, self_x;
242 if can_see_real_jids(whois, occupant) then
243 self_p, self_x = get_full_p();
245 -- Can always see your own full jids
246 -- But not allowed to see actor's
247 self_x = st.clone(base_x);
248 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
249 self_p = st.clone(base_presence):add_child(self_x);
253 for occupant_nick, n_occupant in self:each_occupant() do
254 if occupant_nick ~= occupant.nick then
256 if can_see_real_jids(whois, n_occupant) then
258 elseif occupant.bare_jid == n_occupant.bare_jid then
263 self:route_to_occupant(n_occupant, pr);
267 -- Presences for occupant itself
268 self_x:tag("status", {code = "110";}):up();
269 if occupant.role == nil then
270 -- They get an unavailable
271 self:route_to_occupant(occupant, self_p);
273 -- use their own presences as templates
274 for full_jid, pr in occupant:each_session() do
276 pr.attr.to = full_jid;
277 pr:add_child(self_x);
278 self:route_stanza(pr);
283 function room_mt:send_occupant_list(to, filter)
284 local to_bare = jid_bare(to);
285 local is_anonymous = false;
286 local whois = self:get_whois();
287 if whois ~= "anyone" then
288 local affiliation = self:get_affiliation(to);
289 if affiliation ~= "admin" and affiliation ~= "owner" then
290 local occupant = self:get_occupant_by_real_jid(to);
291 if not (occupant and can_see_real_jids(whois, occupant)) then
296 for occupant_jid, occupant in self:each_occupant() do
297 if filter == nil or filter(occupant_jid, occupant) then
298 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
299 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
300 local pres = st.clone(occupant:get_presence());
303 self:route_stanza(pres);
308 function room_mt:get_disco_info(stanza)
309 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
310 local form = dataform.new {
311 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
314 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form, formdata = formdata ;});
315 reply:add_child(form:form(formdata, "result"));
318 module:hook("muc-disco#info", function(event)
319 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
321 module:hook("muc-disco#info", function(event)
322 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants" });
323 event.formdata["muc#roominfo_occupants"] = tostring(iterators.count(event.room:each_occupant()));
326 function room_mt:get_disco_items(stanza)
327 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
328 for room_jid in self:each_occupant() do
329 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
334 function room_mt:handle_kickable(origin, stanza) -- luacheck: ignore 212
335 local real_jid = stanza.attr.from;
336 local occupant = self:get_occupant_by_real_jid(real_jid);
337 if occupant == nil then return nil; end
338 local type, condition, text = stanza:get_error();
339 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
341 error_message = error_message..": "..text;
343 occupant:set_session(real_jid, st.presence({type="unavailable"})
344 :tag('status'):text(error_message));
345 self:save_occupant(occupant);
346 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
347 :tag("status", {code = "307"})
348 self:publicise_occupant_status(occupant, x);
349 if occupant.jid == real_jid then -- Was last session
350 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
355 -- Give the room creator owner affiliation
356 module:hook("muc-room-pre-create", function(event)
357 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
360 -- check if user is banned
361 module:hook("muc-occupant-pre-join", function(event)
362 local room, stanza = event.room, event.stanza;
363 local affiliation = room:get_affiliation(stanza.attr.from);
364 if affiliation == "outcast" then
365 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
366 reply.tags[1].attr.code = "403";
367 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
372 function room_mt:handle_presence_to_occupant(origin, stanza)
373 local type = stanza.attr.type;
374 if type == "error" then -- error, kick em out!
375 return self:handle_kickable(origin, stanza)
376 elseif type == nil or type == "unavailable" then
377 local real_jid = stanza.attr.from;
378 local bare_jid = jid_bare(real_jid);
379 local orig_occupant, dest_occupant;
380 local is_new_room = next(self._affiliations) == nil;
382 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
383 if module:fire_event("muc-room-pre-create", {
387 }) then return true; end
389 orig_occupant = self:get_occupant_by_real_jid(real_jid);
390 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
392 local is_first_dest_session;
393 if type == "unavailable" then -- luacheck: ignore 542
394 -- FIXME Why the empty if branch?
395 -- dest_occupant = nil
396 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
397 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
398 dest_occupant = orig_occupant;
400 local dest_jid = stanza.attr.to;
401 dest_occupant = self:get_occupant_by_nick(dest_jid);
402 if dest_occupant == nil then
403 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
404 is_first_dest_session = true;
405 dest_occupant = self:new_occupant(bare_jid, dest_jid);
407 is_first_dest_session = false;
410 local is_last_orig_session;
411 if orig_occupant ~= nil then
412 -- Is there are least 2 sessions?
413 local iter, ob, last = orig_occupant:each_session();
414 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
417 local event, event_name = {
421 is_first_session = is_first_dest_session;
422 is_last_session = is_last_orig_session;
424 if orig_occupant == nil then
425 event_name = "muc-occupant-pre-join";
426 event.is_new_room = is_new_room;
427 event.occupant = dest_occupant;
428 elseif dest_occupant == nil then
429 event_name = "muc-occupant-pre-leave";
430 event.occupant = orig_occupant;
432 event_name = "muc-occupant-pre-change";
433 event.orig_occupant = orig_occupant;
434 event.dest_occupant = dest_occupant;
436 if module:fire_event(event_name, event) then return true; end
438 -- Check for nick conflicts
439 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
440 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
441 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
442 reply.tags[1].attr.code = "409";
443 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
447 -- Send presence stanza about original occupant
448 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
449 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
451 if dest_occupant == nil then -- Session is leaving
452 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
453 if is_last_orig_session then
454 orig_occupant.role = nil;
456 orig_occupant:set_session(real_jid, stanza);
458 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
459 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
460 orig_occupant:set_session(real_jid, generated_unavail);
461 dest_nick = select(3, jid_split(dest_occupant.nick));
462 if not is_first_dest_session then -- User is swapping into another pre-existing session
463 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
464 -- Show the other session leaving
465 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
466 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
467 add_item(x, self:get_affiliation(bare_jid), "none");
468 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
470 self:route_stanza(pr);
472 if is_first_dest_session and is_last_orig_session then -- Normal nick change
473 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
474 orig_x:tag("status", {code = "303";}):up();
475 else -- The session itself always needs to see a nick change
476 -- don't want to get our old nick's available presence,
477 -- so remove our session from there, and manually generate an unavailable
478 orig_occupant:remove_session(real_jid);
479 log("debug", "generating nick change for %s", real_jid);
480 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
481 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
482 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
483 x:tag("status", {code = "303";}):up();
484 x:tag("status", {code = "110";}):up();
485 self:route_stanza(generated_unavail:add_child(x));
486 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
489 self:save_occupant(orig_occupant);
490 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
492 if is_last_orig_session then
493 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
497 if dest_occupant ~= nil then
498 dest_occupant:set_session(real_jid, stanza);
499 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
501 dest_x:tag("status", {code = "201"}):up();
503 if orig_occupant == nil and self:get_whois() == "anyone" then
504 dest_x:tag("status", {code = "100"}):up();
506 self:save_occupant(dest_occupant);
508 if orig_occupant == nil then
509 -- Send occupant list to newly joined user
510 self:send_occupant_list(real_jid, function(nick, occupant) -- luacheck: ignore 212
511 -- Don't include self
512 return occupant:get_presence(real_jid) == nil;
515 self:publicise_occupant_status(dest_occupant, dest_x);
517 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
518 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
519 -- Show the original nick joining again
520 local pr = st.clone(orig_occupant:get_presence());
521 pr.attr.to = real_jid;
522 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
523 self:build_item_list(orig_occupant, x, false);
524 -- TODO: new status code to inform client this was the multi-session it left?
526 self:route_stanza(pr);
529 if orig_occupant == nil then
530 if is_first_dest_session then
531 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
533 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
536 elseif type ~= 'result' then -- bad type
537 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
538 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
544 function room_mt:handle_iq_to_occupant(origin, stanza)
545 local from, to = stanza.attr.from, stanza.attr.to;
546 local type = stanza.attr.type;
547 local id = stanza.attr.id;
548 local occupant = self:get_occupant_by_nick(to);
549 if (type == "error" or type == "result") then
550 do -- deconstruct_stanza_id
551 if not occupant then return nil; end
552 local from_jid, orig_id, to_jid_hash = (base64.decode(id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
553 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
554 local from_occupant_jid = self:get_occupant_jid(from_jid);
555 if from_occupant_jid == nil then return nil; end
557 for to_jid in occupant:each_session() do
558 if md5(to_jid) == to_jid_hash then
559 session_jid = to_jid;
563 if session_jid == nil then return nil; end
564 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, orig_id;
566 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
567 self:route_stanza(stanza);
568 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
570 else -- Type is "get" or "set"
571 local current_nick = self:get_occupant_jid(from);
572 if not current_nick then
573 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
576 if not occupant then -- recipient not in room
577 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
580 do -- construct_stanza_id
581 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
583 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
584 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
585 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
586 stanza.attr.to = jid_bare(stanza.attr.to);
588 self:route_stanza(stanza);
589 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
594 function room_mt:handle_message_to_occupant(origin, stanza)
595 local from, to = stanza.attr.from, stanza.attr.to;
596 local current_nick = self:get_occupant_jid(from);
597 local type = stanza.attr.type;
598 if not current_nick then -- not in room
599 if type ~= "error" then
600 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
604 if type == "groupchat" then -- groupchat messages not allowed in PM
605 origin.send(st.error_reply(stanza, "modify", "bad-request"));
607 elseif type == "error" and is_kickable_error(stanza) then
608 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
609 return self:handle_kickable(origin, stanza); -- send unavailable
612 local o_data = self:get_occupant_by_nick(to);
614 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
617 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
618 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
619 stanza.attr.from = current_nick;
620 self:route_to_occupant(o_data, stanza)
621 -- TODO: Remove x tag?
622 stanza.attr.from = from;
626 function room_mt:send_form(origin, stanza)
627 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
628 :add_child(self:get_form_layout(stanza.attr.from):form())
632 function room_mt:get_form_layout(actor)
633 local form = dataform.new({
634 title = "Configuration for "..self.jid,
635 instructions = "Complete and submit this form to configure the room.",
639 value = 'http://jabber.org/protocol/muc#roomconfig'
642 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
645 function room_mt:process_form(origin, stanza)
646 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
647 if form.attr.type == "cancel" then
648 origin.send(st.reply(stanza));
649 elseif form.attr.type == "submit" then
650 local fields, errors, present;
651 if form.tags[1] == nil then -- Instant room
652 fields, present = {}, {};
654 fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
655 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
656 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
661 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
662 function event.update_option(name, field, allowed)
663 local new = fields[field];
664 if new == nil then return; end
665 if allowed and not allowed[new] then return; end
666 if new == self["get_"..name](self) then return; end
667 event.status_codes["104"] = true;
668 self["set_"..name](self, new);
671 module:fire_event("muc-config-submitted", event);
672 for submitted_field in pairs(present) do
673 event.field, event.value = submitted_field, fields[submitted_field];
674 module:fire_event("muc-config-submitted/"..submitted_field, event);
676 event.field, event.value = nil, nil;
678 if self.save then self:save(true); end
679 origin.send(st.reply(stanza));
681 if next(event.status_codes) then
682 local msg = st.message({type='groupchat', from=self.jid})
683 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
684 for code in pairs(event.status_codes) do
685 msg:tag("status", {code = code;}):up();
688 self:broadcast_message(msg);
691 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
696 -- Removes everyone from the room
697 function room_mt:clear(x)
698 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
699 local occupants_updated = {};
700 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
702 self:save_occupant(occupant);
703 occupants_updated[occupant] = true;
705 for occupant in pairs(occupants_updated) do
706 self:publicise_occupant_status(occupant, x);
707 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
711 function room_mt:destroy(newjid, reason, password)
712 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
713 :tag("item", { affiliation='none', role='none' }):up()
714 :tag("destroy", {jid=newjid});
715 if reason then x:tag("reason"):text(reason):up(); end
716 if password then x:tag("password"):text(password):up(); end
719 module:fire_event("muc-room-destroyed", { room = self });
722 function room_mt:handle_disco_info_get_query(origin, stanza)
723 origin.send(self:get_disco_info(stanza));
727 function room_mt:handle_disco_items_get_query(origin, stanza)
728 origin.send(self:get_disco_items(stanza));
732 function room_mt:handle_admin_query_set_command(origin, stanza)
733 local item = stanza.tags[1].tags[1];
735 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
737 if item.attr.jid then -- Validate provided JID
738 item.attr.jid = jid_prep(item.attr.jid);
739 if not item.attr.jid then
740 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
744 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
745 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
746 if occupant then item.attr.jid = occupant.jid; end
747 elseif not item.attr.nick and item.attr.jid then
748 local nick = self:get_occupant_jid(item.attr.jid);
749 if nick then item.attr.nick = select(3, jid_split(nick)); end
751 local actor = stanza.attr.from;
752 local reason = item:get_child_text("reason");
753 local success, errtype, err
754 if item.attr.affiliation and item.attr.jid and not item.attr.role then
755 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
756 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
757 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
759 success, errtype, err = nil, "cancel", "bad-request";
762 origin.send(st.error_reply(stanza, errtype, err));
764 origin.send(st.reply(stanza));
769 function room_mt:handle_admin_query_get_command(origin, stanza)
770 local actor = stanza.attr.from;
771 local affiliation = self:get_affiliation(actor);
772 local item = stanza.tags[1].tags[1];
773 local _aff = item.attr.affiliation;
774 local _aff_rank = valid_affiliations[_aff or "none"];
775 local _rol = item.attr.role;
776 if _aff and _aff_rank and not _rol then
777 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
778 -- e.g. an admin can't ask for a list of owners
779 local affiliation_rank = valid_affiliations[affiliation or "none"];
780 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
781 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
782 for jid in self:each_affiliation(_aff or "none") do
783 reply:tag("item", {affiliation = _aff, jid = jid}):up();
785 origin.send(reply:up());
788 origin.send(st.error_reply(stanza, "auth", "forbidden"));
791 elseif _rol and valid_roles[_rol or "none"] and not _aff then
792 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
793 if valid_roles[role or "none"] >= valid_roles.moderator then
794 if _rol == "none" then _rol = nil; end
795 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
796 -- TODO: whois check here? (though fully anonymous rooms are not supported)
797 for occupant_jid, occupant in self:each_occupant() do
798 if occupant.role == _rol then
799 local nick = select(3,jid_split(occupant_jid));
800 self:build_item_list(occupant, reply, false, nick);
803 origin.send(reply:up());
806 origin.send(st.error_reply(stanza, "auth", "forbidden"));
810 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
815 function room_mt:handle_owner_query_get_to_room(origin, stanza)
816 if self:get_affiliation(stanza.attr.from) ~= "owner" then
817 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
821 self:send_form(origin, stanza);
824 function room_mt:handle_owner_query_set_to_room(origin, stanza)
825 if self:get_affiliation(stanza.attr.from) ~= "owner" then
826 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
830 local child = stanza.tags[1].tags[1];
832 origin.send(st.error_reply(stanza, "modify", "bad-request"));
834 elseif child.name == "destroy" then
835 local newjid = child.attr.jid;
836 local reason = child:get_child_text("reason");
837 local password = child:get_child_text("password");
838 self:destroy(newjid, reason, password);
839 origin.send(st.reply(stanza));
841 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
842 return self:process_form(origin, stanza);
844 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
849 function room_mt:handle_groupchat_to_room(origin, stanza)
850 local from = stanza.attr.from;
851 local occupant = self:get_occupant_by_real_jid(from);
852 if module:fire_event("muc-occupant-groupchat", {
853 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
854 }) then return true; end
855 stanza.attr.from = occupant.nick;
856 self:broadcast_message(stanza);
857 stanza.attr.from = from;
862 module:hook("muc-occupant-groupchat", function(event)
863 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
864 if role_rank <= valid_roles.none then
865 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
867 elseif role_rank <= valid_roles.visitor then
868 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
873 -- hack - some buggy clients send presence updates to the room rather than their nick
874 function room_mt:handle_presence_to_room(origin, stanza)
875 local current_nick = self:get_occupant_jid(stanza.attr.from);
878 local to = stanza.attr.to;
879 stanza.attr.to = current_nick;
880 handled = self:handle_presence_to_occupant(origin, stanza);
886 -- Need visitor role or higher to invite
887 module:hook("muc-pre-invite", function(event)
888 local room, stanza = event.room, event.stanza;
889 local _from = stanza.attr.from;
890 local inviter = room:get_occupant_by_real_jid(_from);
891 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
892 if valid_roles[role or "none"] <= valid_roles.visitor then
893 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
898 function room_mt:handle_mediated_invite(origin, stanza)
899 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
900 local invitee = jid_prep(payload.attr.to);
902 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
904 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
907 local invite = muc_util.filter_muc_x(st.clone(stanza));
908 invite.attr.from = self.jid;
909 invite.attr.to = invitee;
910 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
911 :tag('invite', {from = stanza.attr.from;})
912 :tag('reason'):text(payload:get_child_text("reason")):up()
915 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
916 self:route_stanza(invite);
921 -- COMPAT: Some older clients expect this
922 module:hook("muc-invite", function(event)
923 local room, stanza = event.room, event.stanza;
924 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
925 local reason = invite:get_child_text("reason");
926 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
931 -- Add a plain message for clients which don't support invites
932 module:hook("muc-invite", function(event)
933 local room, stanza = event.room, event.stanza;
934 if not stanza:get_child("body") then
935 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
936 local reason = invite:get_child_text("reason") or "";
938 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
943 function room_mt:handle_mediated_decline(origin, stanza)
944 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
945 local declinee = jid_prep(payload.attr.to);
947 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
949 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
952 local decline = muc_util.filter_muc_x(st.clone(stanza));
953 decline.attr.from = self.jid;
954 decline.attr.to = declinee;
955 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
956 :tag("decline", {from = stanza.attr.from})
957 :tag("reason"):text(payload:get_child_text("reason")):up()
960 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
961 declinee = decline.attr.to; -- re-fetch, in case event modified it
963 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
964 occupant = self:get_occupant_by_nick(declinee);
967 self:route_to_occupant(occupant, decline);
969 self:route_stanza(decline);
975 -- Add a plain message for clients which don't support declines
976 module:hook("muc-decline", function(event)
977 local room, stanza = event.room, event.stanza;
978 if not stanza:get_child("body") then
979 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
980 local reason = decline:get_child_text("reason") or "";
982 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
987 function room_mt:handle_message_to_room(origin, stanza)
988 local type = stanza.attr.type;
989 if type == "groupchat" then
990 return self:handle_groupchat_to_room(origin, stanza)
991 elseif type == "error" and is_kickable_error(stanza) then
992 return self:handle_kickable(origin, stanza)
993 elseif type == nil then
994 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
996 local payload = x.tags[1];
997 if payload == nil then --luacheck: ignore 542
999 elseif payload.name == "invite" and payload.attr.to then
1000 return self:handle_mediated_invite(origin, stanza)
1001 elseif payload.name == "decline" and payload.attr.to then
1002 return self:handle_mediated_decline(origin, stanza)
1004 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1010 function room_mt:route_stanza(stanza) -- luacheck: ignore 212
1011 module:send(stanza);
1014 function room_mt:get_affiliation(jid)
1015 local node, host, resource = jid_split(jid);
1016 local bare = node and node.."@"..host or host;
1017 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1018 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1022 -- Iterates over jid, affiliation pairs
1023 function room_mt:each_affiliation(with_affiliation)
1024 if not with_affiliation then
1025 return pairs(self._affiliations);
1027 return function(_affiliations, jid)
1029 repeat -- Iterate until we get a match
1030 jid, affiliation = next(_affiliations, jid);
1031 until jid == nil or affiliation == with_affiliation
1032 return jid, affiliation;
1033 end, self._affiliations, nil
1037 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1038 if not actor then return nil, "modify", "not-acceptable"; end;
1040 local node, host, resource = jid_split(jid);
1041 if not host then return nil, "modify", "not-acceptable"; end
1042 jid = jid_join(node, host); -- Bare
1043 local is_host_only = node == nil;
1045 if valid_affiliations[affiliation or "none"] == nil then
1046 return nil, "modify", "not-acceptable";
1048 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1050 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1051 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1053 if actor == true then
1054 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1056 local actor_affiliation = self:get_affiliation(actor);
1057 if actor_affiliation == "owner" then
1058 if jid_bare(actor) == jid then -- self change
1059 -- need at least one owner
1060 local is_last = true;
1061 for j in self:each_affiliation("owner") do
1062 if j ~= jid then is_last = false; break; end
1065 return nil, "cancel", "conflict";
1068 -- owners can do anything else
1069 elseif affiliation == "owner" or affiliation == "admin"
1070 or actor_affiliation ~= "admin"
1071 or target_affiliation == "owner" or target_affiliation == "admin" then
1072 -- Can't demote owners or other admins
1073 return nil, "cancel", "not-allowed";
1077 -- Set in 'database'
1078 self._affiliations[jid] = affiliation;
1081 local role = self:get_default_role(affiliation);
1082 local role_rank = valid_roles[role or "none"];
1083 local occupants_updated = {}; -- Filled with old roles
1084 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
1085 if occupant.bare_jid == jid or (
1086 -- Outcast can be by host.
1087 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1089 -- need to publcize in all cases; as affiliation in <item/> has changed.
1090 occupants_updated[occupant] = occupant.role;
1091 if occupant.role ~= role and (
1093 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1095 occupant.role = role;
1096 self:save_occupant(occupant);
1101 -- Tell the room of the new occupant affiliations+roles
1102 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1103 if not role then -- getting kicked
1104 if affiliation == "outcast" then
1105 x:tag("status", {code="301"}):up(); -- banned
1107 x:tag("status", {code="321"}):up(); -- affiliation change
1110 local is_semi_anonymous = self:get_whois() == "moderators";
1111 for occupant, old_role in pairs(occupants_updated) do
1112 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1113 if occupant.role == nil then
1114 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1115 elseif is_semi_anonymous and
1116 (old_role == "moderator" and occupant.role ~= "moderator") or
1117 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1118 -- Send everyone else's presences (as jid visibility has changed)
1119 for real_jid in occupant:each_session() do
1120 self:send_occupant_list(real_jid, function(occupant_jid, occupant) --luacheck: ignore 212 433
1121 return occupant.bare_jid ~= jid;
1127 if self.save then self:save(); end
1129 module:fire_event("muc-set-affiliation", {
1133 affiliation = affiliation or "none";
1135 previous_affiliation = target_affiliation;
1136 in_room = next(occupants_updated) ~= nil;
1142 function room_mt:get_role(nick)
1143 local occupant = self:get_occupant_by_nick(nick);
1144 return occupant and occupant.role or nil;
1147 function room_mt:set_role(actor, occupant_jid, role, reason)
1148 if not actor then return nil, "modify", "not-acceptable"; end
1150 local occupant = self:get_occupant_by_nick(occupant_jid);
1151 if not occupant then return nil, "modify", "not-acceptable"; end
1153 if valid_roles[role or "none"] == nil then
1154 return nil, "modify", "not-acceptable";
1156 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1158 if actor == true then
1159 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1161 -- Can't do anything to other owners or admins
1162 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1163 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1164 return nil, "cancel", "not-allowed";
1167 -- If you are trying to give or take moderator role you need to be an owner or admin
1168 if occupant.role == "moderator" or role == "moderator" then
1169 local actor_affiliation = self:get_affiliation(actor);
1170 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1171 return nil, "cancel", "not-allowed";
1175 -- Need to be in the room and a moderator
1176 local actor_occupant = self:get_occupant_by_real_jid(actor);
1177 if not actor_occupant or actor_occupant.role ~= "moderator" then
1178 return nil, "cancel", "not-allowed";
1182 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1184 x:tag("status", {code = "307"}):up();
1186 occupant.role = role;
1187 self:save_occupant(occupant);
1188 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1190 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1195 local whois = module:require "muc/whois";
1196 room_mt.get_whois = whois.get;
1197 room_mt.set_whois = whois.set;
1199 local _M = {}; -- module "muc"
1201 function _M.new_room(jid, config) -- luacheck: ignore 212
1203 return setmetatable({
1213 _M.room_mt = room_mt;