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 base64 = require "util.encodings".base64;
23 local md5 = require "util.hashes".md5;
25 local log = module._log;
27 local occupant_lib = module:require "muc/occupant"
28 local muc_util = module:require "muc/util";
29 local is_kickable_error = muc_util.is_kickable_error;
30 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
33 room_mt.__index = room_mt;
35 function room_mt:__tostring()
36 return "MUC room ("..self.jid..")";
39 function room_mt.save()
40 -- overriden by mod_muc.lua
43 function room_mt:get_occupant_jid(real_jid)
44 return self._jid_nick[real_jid]
47 function room_mt:get_default_role(affiliation)
48 local role = module:fire_event("muc-get-default-role", {
50 affiliation = affiliation;
51 affiliation_rank = valid_affiliations[affiliation or "none"];
53 return role, valid_roles[role or "none"];
55 module:hook("muc-get-default-role", function(event)
56 if event.affiliation_rank >= valid_affiliations.admin then
58 elseif event.affiliation_rank >= valid_affiliations.none then
63 --- Occupant functions
64 function room_mt:new_occupant(bare_real_jid, nick)
65 local occupant = occupant_lib.new(bare_real_jid, nick);
66 local affiliation = self:get_affiliation(bare_real_jid);
67 occupant.role = self:get_default_role(affiliation);
71 function room_mt:get_occupant_by_nick(nick)
72 local occupant = self._occupants[nick];
73 if occupant == nil then return nil end
74 return occupant_lib.copy(occupant);
78 local function next_copied_occupant(occupants, occupant_jid)
79 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
80 if next_occupant_jid == nil then return nil end
81 return next_occupant_jid, occupant_lib.copy(raw_occupant);
83 -- FIXME Explain what 'read_only' is supposed to be
84 function room_mt:each_occupant(read_only) -- luacheck: ignore 212
85 return next_copied_occupant, self._occupants, nil;
89 function room_mt:has_occupant()
90 return next(self._occupants, nil) ~= nil
93 function room_mt:get_occupant_by_real_jid(real_jid)
94 local occupant_jid = self:get_occupant_jid(real_jid);
95 if occupant_jid == nil then return nil end
96 return self:get_occupant_by_nick(occupant_jid);
99 function room_mt:save_occupant(occupant)
100 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
101 local id = occupant.nick
103 -- Need to maintain _jid_nick secondary index
104 local old_occupant = self._occupants[id];
106 for real_jid in old_occupant:each_session() do
107 self._jid_nick[real_jid] = nil;
111 local has_live_session = false
112 if occupant.role ~= nil then
113 for real_jid, presence in occupant:each_session() do
114 if presence.attr.type == nil then
115 has_live_session = true
116 self._jid_nick[real_jid] = occupant.nick;
119 if not has_live_session then
120 -- Has no live sessions left; they have left the room.
124 if not has_live_session then
127 self._occupants[id] = occupant
130 function room_mt:route_to_occupant(occupant, stanza)
131 local to = stanza.attr.to;
132 for jid in occupant:each_session() do
133 stanza.attr.to = jid;
134 self:route_stanza(stanza);
139 -- actor is the attribute table
140 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
141 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
142 if actor_nick or actor_jid then
143 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
146 x:tag("reason"):text(reason):up()
152 -- actor is (real) jid
153 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
154 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
155 local role = occupant.role or "none";
157 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
159 for real_jid in occupant:each_session() do
160 add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
166 function room_mt:broadcast_message(stanza)
167 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
170 self:broadcast(stanza);
174 -- Broadcast a stanza to all occupants in the room.
175 -- optionally checks conditional called with (nick, occupant)
176 function room_mt:broadcast(stanza, cond_func)
177 for nick, occupant in self:each_occupant() do
178 if cond_func == nil or cond_func(nick, occupant) then
179 self:route_to_occupant(occupant, stanza)
184 local function can_see_real_jids(whois, occupant)
185 if whois == "anyone" then
187 elseif whois == "moderators" then
188 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
192 -- Broadcasts an occupant's presence to the whole room
193 -- Takes the x element that goes into the stanzas
194 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
195 -- Build real jid and (optionally) occupant jid template presences
196 local base_presence do
197 -- Try to use main jid's presence
198 local pr = occupant:get_presence();
199 if pr and (pr.attr.type ~= "unavailable" and occupant.role ~= nil) then
200 base_presence = st.clone(pr);
201 else -- user is leaving but didn't send a leave presence. make one for them
202 base_presence = st.presence {from = occupant.nick; type = "unavailable";};
206 -- Fire event (before full_p and anon_p are created)
208 room = self; stanza = base_presence; x = base_x;
209 occupant = occupant; nick = nick; actor = actor;
212 module:fire_event("muc-broadcast-presence", event);
214 -- Allow muc-broadcast-presence listeners to change things
217 reason = event.reason;
219 local whois = self:get_whois();
223 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
226 local full_p, full_x;
227 local function get_full_p()
228 if full_p == nil then
229 full_x = st.clone(base_x);
230 self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
231 full_p = st.clone(base_presence):add_child(full_x);
233 return full_p, full_x;
236 local anon_p, anon_x;
237 local function get_anon_p()
238 if anon_p == nil then
239 anon_x = st.clone(base_x);
240 self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
241 anon_p = st.clone(base_presence):add_child(anon_x);
243 return anon_p, anon_x;
246 local self_p, self_x;
247 if can_see_real_jids(whois, occupant) then
248 self_p, self_x = get_full_p();
250 -- Can always see your own full jids
251 -- But not allowed to see actor's
252 self_x = st.clone(base_x);
253 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
254 self_p = st.clone(base_presence):add_child(self_x);
258 for occupant_nick, n_occupant in self:each_occupant() do
259 if occupant_nick ~= occupant.nick then
261 if can_see_real_jids(whois, n_occupant) then
263 elseif occupant.bare_jid == n_occupant.bare_jid then
268 self:route_to_occupant(n_occupant, pr);
272 -- Presences for occupant itself
273 self_x:tag("status", {code = "110";}):up();
274 if occupant.role == nil then
275 -- They get an unavailable
276 self:route_to_occupant(occupant, self_p);
278 -- use their own presences as templates
279 for full_jid, pr in occupant:each_session() do
281 pr.attr.to = full_jid;
282 pr:add_child(self_x);
283 self:route_stanza(pr);
288 function room_mt:send_occupant_list(to, filter)
289 local to_bare = jid_bare(to);
290 local is_anonymous = false;
291 local whois = self:get_whois();
292 if whois ~= "anyone" then
293 local affiliation = self:get_affiliation(to);
294 if affiliation ~= "admin" and affiliation ~= "owner" then
295 local occupant = self:get_occupant_by_real_jid(to);
296 if not (occupant and can_see_real_jids(whois, occupant)) then
301 for occupant_jid, occupant in self:each_occupant() do
302 if filter == nil or filter(occupant_jid, occupant) then
303 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
304 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
305 local pres = st.clone(occupant:get_presence());
308 self:route_stanza(pres);
313 function room_mt:get_disco_info(stanza)
314 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
315 local form = dataform.new {
316 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
319 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form, formdata = formdata ;});
320 reply:add_child(form:form(formdata, "result"));
323 module:hook("muc-disco#info", function(event)
324 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
326 module:hook("muc-disco#info", function(event)
327 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants" });
328 event.formdata["muc#roominfo_occupants"] = tostring(iterators.count(event.room:each_occupant()));
331 function room_mt:get_disco_items(stanza)
332 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
333 for room_jid in self:each_occupant() do
334 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
339 function room_mt:handle_kickable(origin, stanza) -- luacheck: ignore 212
340 local real_jid = stanza.attr.from;
341 local occupant = self:get_occupant_by_real_jid(real_jid);
342 if occupant == nil then return nil; end
343 local type, condition, text = stanza:get_error();
344 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
346 error_message = error_message..": "..text;
348 occupant:set_session(real_jid, st.presence({type="unavailable"})
349 :tag('status'):text(error_message));
350 self:save_occupant(occupant);
351 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
352 :tag("status", {code = "307"})
353 self:publicise_occupant_status(occupant, x);
354 if occupant.jid == real_jid then -- Was last session
355 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
360 if not module:get_option_boolean("muc_compat_create", true) then
361 module:hook("muc-room-pre-create", function(event)
362 local origin, stanza = event.origin, event.stanza;
363 if not stanza:get_child("x", "http://jabber.org/protocol/muc") then
364 origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
370 -- Give the room creator owner affiliation
371 module:hook("muc-room-pre-create", function(event)
372 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
375 -- check if user is banned
376 module:hook("muc-occupant-pre-join", function(event)
377 local room, stanza = event.room, event.stanza;
378 local affiliation = room:get_affiliation(stanza.attr.from);
379 if affiliation == "outcast" then
380 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
381 reply.tags[1].attr.code = "403";
382 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
387 function room_mt:handle_first_presence(origin, stanza)
388 local real_jid = stanza.attr.from;
389 local dest_jid = stanza.attr.to;
390 local bare_jid = jid_bare(real_jid);
391 if module:fire_event("muc-room-pre-create", {
395 }) then return true; end
396 local is_first_dest_session = true;
397 local dest_occupant = self:new_occupant(bare_jid, dest_jid);
399 -- TODO Handle this case sensibly
400 if not stanza:get_child("x", "http://jabber.org/protocol/muc") then
401 module:log("debug", "Room creation without <x>, possibly desynced");
404 if module:fire_event("muc-occupant-pre-join", {
408 is_first_session = is_first_dest_session;
410 occupant = dest_occupant;
411 }) then return true; end
413 dest_occupant:set_session(real_jid, stanza);
414 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
415 dest_x:tag("status", {code = "201"}):up();
416 if self:get_whois() == "anyone" then
417 dest_x:tag("status", {code = "100"}):up();
419 self:save_occupant(dest_occupant);
421 self:publicise_occupant_status(dest_occupant, dest_x);
423 module:fire_event("muc-occupant-joined", {
425 nick = dest_occupant.nick;
426 occupant = dest_occupant;
430 module:fire_event("muc-occupant-session-new", {
432 nick = dest_occupant.nick;
433 occupant = dest_occupant;
438 module:fire_event("muc-room-created", {
440 creator = dest_occupant;
447 function room_mt:handle_normal_presence(origin, stanza)
448 local type = stanza.attr.type;
449 local real_jid = stanza.attr.from;
450 local bare_jid = jid_bare(real_jid);
451 local orig_occupant = self:get_occupant_by_real_jid(real_jid);
452 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
453 local is_first_dest_session;
455 if type == "unavailable" then -- luacheck: ignore 542
456 -- FIXME Why the empty if branch?
457 -- dest_occupant = nil
458 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
459 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
460 dest_occupant = orig_occupant;
462 local dest_jid = stanza.attr.to;
463 dest_occupant = self:get_occupant_by_nick(dest_jid);
464 if dest_occupant == nil then
465 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
466 is_first_dest_session = true;
467 dest_occupant = self:new_occupant(bare_jid, dest_jid);
469 is_first_dest_session = false;
472 local is_last_orig_session;
473 if orig_occupant ~= nil then
474 -- Is there are least 2 sessions?
475 local iter, ob, last = orig_occupant:each_session();
476 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
479 -- TODO Handle these cases sensibly
480 local muc_x = stanza:get_child("x", "http://jabber.org/protocol/muc");
481 if orig_occupant == nil and not muc_x then
482 module:log("debug", "Join without <x>, possibly desynced");
483 elseif orig_occupant ~= nil and muc_x then
484 module:log("debug", "Presence update with <x>, possibly desynced");
487 local event, event_name = {
491 is_first_session = is_first_dest_session;
492 is_last_session = is_last_orig_session;
494 if orig_occupant == nil then
495 event_name = "muc-occupant-pre-join";
496 event.occupant = dest_occupant;
497 elseif dest_occupant == nil then
498 event_name = "muc-occupant-pre-leave";
499 event.occupant = orig_occupant;
501 event_name = "muc-occupant-pre-change";
502 event.orig_occupant = orig_occupant;
503 event.dest_occupant = dest_occupant;
505 if module:fire_event(event_name, event) then return true; end
507 -- Check for nick conflicts
508 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
509 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
510 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
511 reply.tags[1].attr.code = "409";
512 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
516 -- Send presence stanza about original occupant
517 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
518 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
520 if dest_occupant == nil then -- Session is leaving
521 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
522 if is_last_orig_session then
523 orig_occupant.role = nil;
525 orig_occupant:set_session(real_jid, stanza);
527 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
528 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
529 orig_occupant:set_session(real_jid, generated_unavail);
530 dest_nick = select(3, jid_split(dest_occupant.nick));
531 if not is_first_dest_session then -- User is swapping into another pre-existing session
532 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
533 -- Show the other session leaving
534 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
535 add_item(x, self:get_affiliation(bare_jid), "none");
536 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
537 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up()
539 self:route_stanza(pr);
541 if is_first_dest_session and is_last_orig_session then -- Normal nick change
542 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
543 orig_x:tag("status", {code = "303";}):up();
544 else -- The session itself always needs to see a nick change
545 -- don't want to get our old nick's available presence,
546 -- so remove our session from there, and manually generate an unavailable
547 orig_occupant:remove_session(real_jid);
548 log("debug", "generating nick change for %s", real_jid);
549 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
550 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
551 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
552 x:tag("status", {code = "303";}):up();
553 x:tag("status", {code = "110";}):up();
554 self:route_stanza(generated_unavail:add_child(x));
555 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
558 self:save_occupant(orig_occupant);
559 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
561 if is_last_orig_session then
562 module:fire_event("muc-occupant-left", {
564 nick = orig_occupant.nick;
565 occupant = orig_occupant;
572 if dest_occupant ~= nil then
573 dest_occupant:set_session(real_jid, stanza);
574 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
575 if orig_occupant == nil and self:get_whois() == "anyone" then
576 dest_x:tag("status", {code = "100"}):up();
578 self:save_occupant(dest_occupant);
580 if orig_occupant == nil or muc_x then
581 -- Send occupant list to newly joined user
582 self:send_occupant_list(real_jid, function(nick, occupant) -- luacheck: ignore 212
583 -- Don't include self
584 return occupant:get_presence(real_jid) == nil;
587 self:publicise_occupant_status(dest_occupant, dest_x);
589 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
590 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
591 -- Show the original nick joining again
592 local pr = st.clone(orig_occupant:get_presence());
593 pr.attr.to = real_jid;
594 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
595 self:build_item_list(orig_occupant, x, false);
596 -- TODO: new status code to inform client this was the multi-session it left?
598 self:route_stanza(pr);
601 if orig_occupant == nil or muc_x then
602 if is_first_dest_session then
603 module:fire_event("muc-occupant-joined", {
605 nick = dest_occupant.nick;
606 occupant = dest_occupant;
611 module:fire_event("muc-occupant-session-new", {
613 nick = dest_occupant.nick;
614 occupant = dest_occupant;
624 function room_mt:handle_presence_to_occupant(origin, stanza)
625 local type = stanza.attr.type;
626 if type == "error" then -- error, kick em out!
627 return self:handle_kickable(origin, stanza)
628 elseif type == nil or type == "unavailable" then
629 return self:handle_normal_presence(origin, stanza);
630 elseif type ~= 'result' then -- bad type
631 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
632 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
638 function room_mt:handle_iq_to_occupant(origin, stanza)
639 local from, to = stanza.attr.from, stanza.attr.to;
640 local type = stanza.attr.type;
641 local id = stanza.attr.id;
642 local occupant = self:get_occupant_by_nick(to);
643 if (type == "error" or type == "result") then
644 do -- deconstruct_stanza_id
645 if not occupant then return nil; end
646 local from_jid, orig_id, to_jid_hash = (base64.decode(id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
647 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
648 local from_occupant_jid = self:get_occupant_jid(from_jid);
649 if from_occupant_jid == nil then return nil; end
651 for to_jid in occupant:each_session() do
652 if md5(to_jid) == to_jid_hash then
653 session_jid = to_jid;
657 if session_jid == nil then return nil; end
658 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, orig_id;
660 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
661 self:route_stanza(stanza);
662 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
664 else -- Type is "get" or "set"
665 local current_nick = self:get_occupant_jid(from);
666 if not current_nick then
667 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
670 if not occupant then -- recipient not in room
671 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
674 do -- construct_stanza_id
675 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
677 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
678 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
679 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
680 stanza.attr.to = jid_bare(stanza.attr.to);
682 self:route_stanza(stanza);
683 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
688 function room_mt:handle_message_to_occupant(origin, stanza)
689 local from, to = stanza.attr.from, stanza.attr.to;
690 local current_nick = self:get_occupant_jid(from);
691 local type = stanza.attr.type;
692 if not current_nick then -- not in room
693 if type ~= "error" then
694 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
698 if type == "groupchat" then -- groupchat messages not allowed in PM
699 origin.send(st.error_reply(stanza, "modify", "bad-request"));
701 elseif type == "error" and is_kickable_error(stanza) then
702 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
703 return self:handle_kickable(origin, stanza); -- send unavailable
706 local o_data = self:get_occupant_by_nick(to);
708 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
711 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
712 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
713 stanza.attr.from = current_nick;
714 self:route_to_occupant(o_data, stanza)
715 -- TODO: Remove x tag?
716 stanza.attr.from = from;
720 function room_mt:send_form(origin, stanza)
721 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
722 :add_child(self:get_form_layout(stanza.attr.from):form())
726 function room_mt:get_form_layout(actor)
727 local form = dataform.new({
728 title = "Configuration for "..self.jid,
729 instructions = "Complete and submit this form to configure the room.",
733 value = 'http://jabber.org/protocol/muc#roomconfig'
736 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
739 function room_mt:process_form(origin, stanza)
740 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
741 if form.attr.type == "cancel" then
742 origin.send(st.reply(stanza));
743 elseif form.attr.type == "submit" then
744 local fields, errors, present;
745 if form.tags[1] == nil then -- Instant room
746 fields, present = {}, {};
748 fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
749 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
750 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
755 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
756 function event.update_option(name, field, allowed)
757 local new = fields[field];
758 if new == nil then return; end
759 if allowed and not allowed[new] then return; end
760 if new == self["get_"..name](self) then return; end
761 event.status_codes["104"] = true;
762 self["set_"..name](self, new);
765 module:fire_event("muc-config-submitted", event);
766 for submitted_field in pairs(present) do
767 event.field, event.value = submitted_field, fields[submitted_field];
768 module:fire_event("muc-config-submitted/"..submitted_field, event);
770 event.field, event.value = nil, nil;
773 origin.send(st.reply(stanza));
775 if next(event.status_codes) then
776 local msg = st.message({type='groupchat', from=self.jid})
777 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
778 for code in pairs(event.status_codes) do
779 msg:tag("status", {code = code;}):up();
782 self:broadcast_message(msg);
785 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
790 -- Removes everyone from the room
791 function room_mt:clear(x)
792 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
793 local occupants_updated = {};
794 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
796 self:save_occupant(occupant);
797 occupants_updated[occupant] = true;
799 for occupant in pairs(occupants_updated) do
800 self:publicise_occupant_status(occupant, x);
801 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
805 function room_mt:destroy(newjid, reason, password)
806 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
807 :tag("item", { affiliation='none', role='none' }):up()
808 :tag("destroy", {jid=newjid});
809 if reason then x:tag("reason"):text(reason):up(); end
810 if password then x:tag("password"):text(password):up(); end
813 module:fire_event("muc-room-destroyed", { room = self });
816 function room_mt:handle_disco_info_get_query(origin, stanza)
817 origin.send(self:get_disco_info(stanza));
821 function room_mt:handle_disco_items_get_query(origin, stanza)
822 origin.send(self:get_disco_items(stanza));
826 function room_mt:handle_admin_query_set_command(origin, stanza)
827 local item = stanza.tags[1].tags[1];
829 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
831 if item.attr.jid then -- Validate provided JID
832 item.attr.jid = jid_prep(item.attr.jid);
833 if not item.attr.jid then
834 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
838 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
839 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
840 if occupant then item.attr.jid = occupant.jid; end
841 elseif not item.attr.nick and item.attr.jid then
842 local nick = self:get_occupant_jid(item.attr.jid);
843 if nick then item.attr.nick = select(3, jid_split(nick)); end
845 local actor = stanza.attr.from;
846 local reason = item:get_child_text("reason");
847 local success, errtype, err
848 if item.attr.affiliation and item.attr.jid and not item.attr.role then
849 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
850 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
851 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
853 success, errtype, err = nil, "cancel", "bad-request";
857 origin.send(st.error_reply(stanza, errtype, err));
859 origin.send(st.reply(stanza));
864 function room_mt:handle_admin_query_get_command(origin, stanza)
865 local actor = stanza.attr.from;
866 local affiliation = self:get_affiliation(actor);
867 local item = stanza.tags[1].tags[1];
868 local _aff = item.attr.affiliation;
869 local _aff_rank = valid_affiliations[_aff or "none"];
870 local _rol = item.attr.role;
871 if _aff and _aff_rank and not _rol then
872 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
873 -- e.g. an admin can't ask for a list of owners
874 local affiliation_rank = valid_affiliations[affiliation or "none"];
875 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank
876 or self:get_members_only() and self:get_whois() == "anyone" and affiliation_rank >= valid_affiliations.member then
877 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
878 for jid in self:each_affiliation(_aff or "none") do
879 reply:tag("item", {affiliation = _aff, jid = jid}):up();
881 origin.send(reply:up());
884 origin.send(st.error_reply(stanza, "auth", "forbidden"));
887 elseif _rol and valid_roles[_rol or "none"] and not _aff then
888 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
889 if valid_roles[role or "none"] >= valid_roles.moderator then
890 if _rol == "none" then _rol = nil; end
891 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
892 -- TODO: whois check here? (though fully anonymous rooms are not supported)
893 for occupant_jid, occupant in self:each_occupant() do
894 if occupant.role == _rol then
895 local nick = select(3,jid_split(occupant_jid));
896 self:build_item_list(occupant, reply, false, nick);
899 origin.send(reply:up());
902 origin.send(st.error_reply(stanza, "auth", "forbidden"));
906 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
911 function room_mt:handle_owner_query_get_to_room(origin, stanza)
912 if self:get_affiliation(stanza.attr.from) ~= "owner" then
913 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
917 self:send_form(origin, stanza);
920 function room_mt:handle_owner_query_set_to_room(origin, stanza)
921 if self:get_affiliation(stanza.attr.from) ~= "owner" then
922 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
926 local child = stanza.tags[1].tags[1];
928 origin.send(st.error_reply(stanza, "modify", "bad-request"));
930 elseif child.name == "destroy" then
931 local newjid = child.attr.jid;
932 local reason = child:get_child_text("reason");
933 local password = child:get_child_text("password");
934 self:destroy(newjid, reason, password);
935 origin.send(st.reply(stanza));
937 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
938 return self:process_form(origin, stanza);
940 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
945 function room_mt:handle_groupchat_to_room(origin, stanza)
946 local from = stanza.attr.from;
947 local occupant = self:get_occupant_by_real_jid(from);
948 if module:fire_event("muc-occupant-groupchat", {
949 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
950 }) then return true; end
951 stanza.attr.from = occupant.nick;
952 self:broadcast_message(stanza);
953 stanza.attr.from = from;
958 module:hook("muc-occupant-groupchat", function(event)
959 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
960 if role_rank <= valid_roles.none then
961 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
963 elseif role_rank <= valid_roles.visitor then
964 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
969 -- hack - some buggy clients send presence updates to the room rather than their nick
970 function room_mt:handle_presence_to_room(origin, stanza)
971 local current_nick = self:get_occupant_jid(stanza.attr.from);
974 local to = stanza.attr.to;
975 stanza.attr.to = current_nick;
976 handled = self:handle_presence_to_occupant(origin, stanza);
982 -- Need visitor role or higher to invite
983 module:hook("muc-pre-invite", function(event)
984 local room, stanza = event.room, event.stanza;
985 local _from = stanza.attr.from;
986 local inviter = room:get_occupant_by_real_jid(_from);
987 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
988 if valid_roles[role or "none"] <= valid_roles.visitor then
989 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
994 function room_mt:handle_mediated_invite(origin, stanza)
995 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
996 local invitee = jid_prep(payload.attr.to);
998 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
1000 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
1003 local invite = muc_util.filter_muc_x(st.clone(stanza));
1004 invite.attr.from = self.jid;
1005 invite.attr.to = invitee;
1006 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
1007 :tag('invite', {from = stanza.attr.from;})
1008 :tag('reason'):text(payload:get_child_text("reason")):up()
1011 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
1012 self:route_stanza(invite);
1017 -- COMPAT: Some older clients expect this
1018 module:hook("muc-invite", function(event)
1019 local room, stanza = event.room, event.stanza;
1020 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
1021 local reason = invite:get_child_text("reason");
1022 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
1027 -- Add a plain message for clients which don't support invites
1028 module:hook("muc-invite", function(event)
1029 local room, stanza = event.room, event.stanza;
1030 if not stanza:get_child("body") then
1031 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
1032 local reason = invite:get_child_text("reason") or "";
1034 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
1039 function room_mt:handle_mediated_decline(origin, stanza)
1040 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
1041 local declinee = jid_prep(payload.attr.to);
1042 if not declinee then
1043 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
1045 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
1048 local decline = muc_util.filter_muc_x(st.clone(stanza));
1049 decline.attr.from = self.jid;
1050 decline.attr.to = declinee;
1051 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1052 :tag("decline", {from = stanza.attr.from})
1053 :tag("reason"):text(payload:get_child_text("reason")):up()
1056 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
1057 declinee = decline.attr.to; -- re-fetch, in case event modified it
1059 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
1060 occupant = self:get_occupant_by_nick(declinee);
1063 self:route_to_occupant(occupant, decline);
1065 self:route_stanza(decline);
1071 -- Add a plain message for clients which don't support declines
1072 module:hook("muc-decline", function(event)
1073 local room, stanza = event.room, event.stanza;
1074 if not stanza:get_child("body") then
1075 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
1076 local reason = decline:get_child_text("reason") or "";
1078 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
1083 function room_mt:handle_message_to_room(origin, stanza)
1084 local type = stanza.attr.type;
1085 if type == "groupchat" then
1086 return self:handle_groupchat_to_room(origin, stanza)
1087 elseif type == "error" and is_kickable_error(stanza) then
1088 return self:handle_kickable(origin, stanza)
1089 elseif type == nil then
1090 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1092 local payload = x.tags[1];
1093 if payload == nil then --luacheck: ignore 542
1095 elseif payload.name == "invite" and payload.attr.to then
1096 return self:handle_mediated_invite(origin, stanza)
1097 elseif payload.name == "decline" and payload.attr.to then
1098 return self:handle_mediated_decline(origin, stanza)
1100 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1106 function room_mt:route_stanza(stanza) -- luacheck: ignore 212
1107 module:send(stanza);
1110 function room_mt:get_affiliation(jid)
1111 local node, host, resource = jid_split(jid);
1112 local bare = node and node.."@"..host or host;
1113 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1114 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1118 -- Iterates over jid, affiliation pairs
1119 function room_mt:each_affiliation(with_affiliation)
1120 if not with_affiliation then
1121 return pairs(self._affiliations);
1123 return function(_affiliations, jid)
1125 repeat -- Iterate until we get a match
1126 jid, affiliation = next(_affiliations, jid);
1127 until jid == nil or affiliation == with_affiliation
1128 return jid, affiliation;
1129 end, self._affiliations, nil
1133 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1134 if not actor then return nil, "modify", "not-acceptable"; end;
1136 local node, host, resource = jid_split(jid);
1137 if not host then return nil, "modify", "not-acceptable"; end
1138 jid = jid_join(node, host); -- Bare
1139 local is_host_only = node == nil;
1141 if valid_affiliations[affiliation or "none"] == nil then
1142 return nil, "modify", "not-acceptable";
1144 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1146 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1147 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1149 if actor == true then
1150 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1152 local actor_affiliation = self:get_affiliation(actor);
1153 if actor_affiliation == "owner" then
1154 if jid_bare(actor) == jid then -- self change
1155 -- need at least one owner
1156 local is_last = true;
1157 for j in self:each_affiliation("owner") do
1158 if j ~= jid then is_last = false; break; end
1161 return nil, "cancel", "conflict";
1164 -- owners can do anything else
1165 elseif affiliation == "owner" or affiliation == "admin"
1166 or actor_affiliation ~= "admin"
1167 or target_affiliation == "owner" or target_affiliation == "admin" then
1168 -- Can't demote owners or other admins
1169 return nil, "cancel", "not-allowed";
1173 -- Set in 'database'
1174 self._affiliations[jid] = affiliation;
1177 local role = self:get_default_role(affiliation);
1178 local role_rank = valid_roles[role or "none"];
1179 local occupants_updated = {}; -- Filled with old roles
1180 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
1181 if occupant.bare_jid == jid or (
1182 -- Outcast can be by host.
1183 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1185 -- need to publcize in all cases; as affiliation in <item/> has changed.
1186 occupants_updated[occupant] = occupant.role;
1187 if occupant.role ~= role and (
1189 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1191 occupant.role = role;
1192 self:save_occupant(occupant);
1197 -- Tell the room of the new occupant affiliations+roles
1198 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1199 if not role then -- getting kicked
1200 if affiliation == "outcast" then
1201 x:tag("status", {code="301"}):up(); -- banned
1203 x:tag("status", {code="321"}):up(); -- affiliation change
1206 local is_semi_anonymous = self:get_whois() == "moderators";
1207 for occupant, old_role in pairs(occupants_updated) do
1208 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1209 if occupant.role == nil then
1210 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1211 elseif is_semi_anonymous and
1212 (old_role == "moderator" and occupant.role ~= "moderator") or
1213 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1214 -- Send everyone else's presences (as jid visibility has changed)
1215 for real_jid in occupant:each_session() do
1216 self:send_occupant_list(real_jid, function(occupant_jid, occupant) --luacheck: ignore 212 433
1217 return occupant.bare_jid ~= jid;
1225 module:fire_event("muc-set-affiliation", {
1229 affiliation = affiliation or "none";
1231 previous_affiliation = target_affiliation;
1232 in_room = next(occupants_updated) ~= nil;
1238 function room_mt:get_role(nick)
1239 local occupant = self:get_occupant_by_nick(nick);
1240 return occupant and occupant.role or nil;
1243 function room_mt:set_role(actor, occupant_jid, role, reason)
1244 if not actor then return nil, "modify", "not-acceptable"; end
1246 local occupant = self:get_occupant_by_nick(occupant_jid);
1247 if not occupant then return nil, "modify", "item-not-found"; end
1249 if valid_roles[role or "none"] == nil then
1250 return nil, "modify", "not-acceptable";
1252 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1254 if actor == true then
1255 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1257 -- Can't do anything to other owners or admins
1258 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1259 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1260 return nil, "cancel", "not-allowed";
1263 -- If you are trying to give or take moderator role you need to be an owner or admin
1264 if occupant.role == "moderator" or role == "moderator" then
1265 local actor_affiliation = self:get_affiliation(actor);
1266 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1267 return nil, "cancel", "not-allowed";
1271 -- Need to be in the room and a moderator
1272 local actor_occupant = self:get_occupant_by_real_jid(actor);
1273 if not actor_occupant or actor_occupant.role ~= "moderator" then
1274 return nil, "cancel", "not-allowed";
1278 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1280 x:tag("status", {code = "307"}):up();
1282 occupant.role = role;
1283 self:save_occupant(occupant);
1284 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1286 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1291 local whois = module:require "muc/whois";
1292 room_mt.get_whois = whois.get;
1293 room_mt.set_whois = whois.set;
1295 local _M = {}; -- module "muc"
1297 function _M.new_room(jid, config)
1298 return setmetatable({
1302 _data = config or {};
1307 function room_mt:freeze(live)
1308 local frozen, state = {
1312 for user, affiliation in pairs(self._affiliations) do
1313 frozen[user] = affiliation;
1317 for nick, occupant in self:each_occupant() do
1319 bare_jid = occupant.bare_jid;
1320 role = occupant.role;
1323 for jid, presence in occupant:each_session() do
1324 state[jid] = st.preserialize(presence);
1327 local history = self._history;
1329 state._last_message = st.preserialize(history[#history].stanza);
1330 state._last_message_at = history[#history].timestamp;
1333 return frozen, state;
1336 function _M.restore_room(frozen, state)
1338 if frozen.jid and frozen._affiliations then
1339 local room = _M.new_room(frozen.jid, frozen._data);
1340 room._affiliations = frozen._affiliations;
1344 local room_jid = frozen._jid;
1345 local room = _M.new_room(room_jid, frozen._data);
1347 if state and state._last_message and state._last_message_at then
1349 { stanza = st.deserialize(state._last_message),
1350 timestamp = state._last_message_at, },
1354 local occupants = {};
1355 local occupant_sessions = {};
1356 local room_name, room_host = jid_split(room_jid);
1357 for jid, data in pairs(frozen) do
1358 local node, host, resource = jid_split(jid);
1359 if host:sub(1,1) ~= "_" and not resource and type(data) == "string" then
1360 -- bare jid: affiliation
1361 room._affiliations[jid] = data;
1364 for jid, data in pairs(state or frozen) do
1365 local node, host, resource = jid_split(jid);
1366 if node or host:sub(1,1) ~= "_" then
1367 if host == room_host and node == room_name and resource and type(data) == "table" then
1368 -- full room jid: bare real jid and role
1369 local bare_jid = data.bare_jid;
1370 local occupant = occupant_lib.new(bare_jid, jid);
1371 occupant.jid = data.jid;
1372 occupant.role = data.role;
1373 occupants[bare_jid] = occupant;
1374 local sessions = occupant_sessions[bare_jid];
1376 for full_jid, presence in pairs(sessions) do
1377 occupant:set_session(full_jid, presence);
1380 occupant_sessions[bare_jid] = nil;
1381 elseif type(data) == "table" and data.name then
1382 -- full user jid: presence
1383 local presence = st.deserialize(data);
1384 local bare_jid = jid_bare(jid);
1385 local occupant = occupants[bare_jid];
1386 local sessions = occupant_sessions[bare_jid];
1388 occupant:set_session(jid, presence);
1389 elseif sessions then
1390 sessions[jid] = presence;
1392 occupant_sessions[bare_jid] = {
1400 for _, occupant in pairs(occupants) do
1401 room:save_occupant(occupant);
1407 _M.room_mt = room_mt;