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" };
313 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
314 reply:add_child(form:form(nil, "result"));
317 module:hook("muc-disco#info", function(event)
318 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
320 module:hook("muc-disco#info", function(event)
321 local count = iterators.count(event.room:each_occupant());
322 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
325 function room_mt:get_disco_items(stanza)
326 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
327 for room_jid in self:each_occupant() do
328 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
333 function room_mt:handle_kickable(origin, stanza) -- luacheck: ignore 212
334 local real_jid = stanza.attr.from;
335 local occupant = self:get_occupant_by_real_jid(real_jid);
336 if occupant == nil then return nil; end
337 local type, condition, text = stanza:get_error();
338 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
340 error_message = error_message..": "..text;
342 occupant:set_session(real_jid, st.presence({type="unavailable"})
343 :tag('status'):text(error_message));
344 self:save_occupant(occupant);
345 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
346 :tag("status", {code = "307"})
347 self:publicise_occupant_status(occupant, x);
348 if occupant.jid == real_jid then -- Was last session
349 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
354 -- Give the room creator owner affiliation
355 module:hook("muc-room-pre-create", function(event)
356 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
359 -- check if user is banned
360 module:hook("muc-occupant-pre-join", function(event)
361 local room, stanza = event.room, event.stanza;
362 local affiliation = room:get_affiliation(stanza.attr.from);
363 if affiliation == "outcast" then
364 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
365 reply.tags[1].attr.code = "403";
366 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
371 function room_mt:handle_presence_to_occupant(origin, stanza)
372 local type = stanza.attr.type;
373 if type == "error" then -- error, kick em out!
374 return self:handle_kickable(origin, stanza)
375 elseif type == nil or type == "unavailable" then
376 local real_jid = stanza.attr.from;
377 local bare_jid = jid_bare(real_jid);
378 local orig_occupant, dest_occupant;
379 local is_new_room = next(self._affiliations) == nil;
381 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
382 if module:fire_event("muc-room-pre-create", {
386 }) then return true; end
388 orig_occupant = self:get_occupant_by_real_jid(real_jid);
389 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
391 local is_first_dest_session;
392 if type == "unavailable" then -- luacheck: ignore 542
393 -- FIXME Why the empty if branch?
394 -- dest_occupant = nil
395 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
396 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
397 dest_occupant = orig_occupant;
399 local dest_jid = stanza.attr.to;
400 dest_occupant = self:get_occupant_by_nick(dest_jid);
401 if dest_occupant == nil then
402 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
403 is_first_dest_session = true;
404 dest_occupant = self:new_occupant(bare_jid, dest_jid);
406 is_first_dest_session = false;
409 local is_last_orig_session;
410 if orig_occupant ~= nil then
411 -- Is there are least 2 sessions?
412 local iter, ob, last = orig_occupant:each_session();
413 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
416 local event, event_name = {
420 is_first_session = is_first_dest_session;
421 is_last_session = is_last_orig_session;
423 if orig_occupant == nil then
424 event_name = "muc-occupant-pre-join";
425 event.is_new_room = is_new_room;
426 event.occupant = dest_occupant;
427 elseif dest_occupant == nil then
428 event_name = "muc-occupant-pre-leave";
429 event.occupant = orig_occupant;
431 event_name = "muc-occupant-pre-change";
432 event.orig_occupant = orig_occupant;
433 event.dest_occupant = dest_occupant;
435 if module:fire_event(event_name, event) then return true; end
437 -- Check for nick conflicts
438 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
439 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
440 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
441 reply.tags[1].attr.code = "409";
442 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
446 -- Send presence stanza about original occupant
447 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
448 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
450 if dest_occupant == nil then -- Session is leaving
451 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
452 if is_last_orig_session then
453 orig_occupant.role = nil;
455 orig_occupant:set_session(real_jid, stanza);
457 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
458 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
459 orig_occupant:set_session(real_jid, generated_unavail);
460 dest_nick = select(3, jid_split(dest_occupant.nick));
461 if not is_first_dest_session then -- User is swapping into another pre-existing session
462 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
463 -- Show the other session leaving
464 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
465 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
466 add_item(x, self:get_affiliation(bare_jid), "none");
467 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
469 self:route_stanza(pr);
471 if is_first_dest_session and is_last_orig_session then -- Normal nick change
472 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
473 orig_x:tag("status", {code = "303";}):up();
474 else -- The session itself always needs to see a nick change
475 -- don't want to get our old nick's available presence,
476 -- so remove our session from there, and manually generate an unavailable
477 orig_occupant:remove_session(real_jid);
478 log("debug", "generating nick change for %s", real_jid);
479 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
480 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
481 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
482 x:tag("status", {code = "303";}):up();
483 x:tag("status", {code = "110";}):up();
484 self:route_stanza(generated_unavail:add_child(x));
485 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
488 self:save_occupant(orig_occupant);
489 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
491 if is_last_orig_session then
492 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
496 if dest_occupant ~= nil then
497 dest_occupant:set_session(real_jid, stanza);
498 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
500 dest_x:tag("status", {code = "201"}):up();
502 if orig_occupant == nil and self:get_whois() == "anyone" then
503 dest_x:tag("status", {code = "100"}):up();
505 self:save_occupant(dest_occupant);
507 if orig_occupant == nil then
508 -- Send occupant list to newly joined user
509 self:send_occupant_list(real_jid, function(nick, occupant) -- luacheck: ignore 212
510 -- Don't include self
511 return occupant:get_presence(real_jid) == nil;
514 self:publicise_occupant_status(dest_occupant, dest_x);
516 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
517 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
518 -- Show the original nick joining again
519 local pr = st.clone(orig_occupant:get_presence());
520 pr.attr.to = real_jid;
521 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
522 self:build_item_list(orig_occupant, x, false);
523 -- TODO: new status code to inform client this was the multi-session it left?
525 self:route_stanza(pr);
528 if orig_occupant == nil then
529 if is_first_dest_session then
530 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
532 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
535 elseif type ~= 'result' then -- bad type
536 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
537 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
543 function room_mt:handle_iq_to_occupant(origin, stanza)
544 local from, to = stanza.attr.from, stanza.attr.to;
545 local type = stanza.attr.type;
546 local id = stanza.attr.id;
547 local occupant = self:get_occupant_by_nick(to);
548 if (type == "error" or type == "result") then
549 do -- deconstruct_stanza_id
550 if not occupant then return nil; end
551 local from_jid, orig_id, to_jid_hash = (base64.decode(id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
552 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
553 local from_occupant_jid = self:get_occupant_jid(from_jid);
554 if from_occupant_jid == nil then return nil; end
556 for to_jid in occupant:each_session() do
557 if md5(to_jid) == to_jid_hash then
558 session_jid = to_jid;
562 if session_jid == nil then return nil; end
563 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, orig_id;
565 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
566 self:route_stanza(stanza);
567 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
569 else -- Type is "get" or "set"
570 local current_nick = self:get_occupant_jid(from);
571 if not current_nick then
572 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
575 if not occupant then -- recipient not in room
576 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
579 do -- construct_stanza_id
580 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
582 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
583 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
584 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
585 stanza.attr.to = jid_bare(stanza.attr.to);
587 self:route_stanza(stanza);
588 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
593 function room_mt:handle_message_to_occupant(origin, stanza)
594 local from, to = stanza.attr.from, stanza.attr.to;
595 local current_nick = self:get_occupant_jid(from);
596 local type = stanza.attr.type;
597 if not current_nick then -- not in room
598 if type ~= "error" then
599 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
603 if type == "groupchat" then -- groupchat messages not allowed in PM
604 origin.send(st.error_reply(stanza, "modify", "bad-request"));
606 elseif type == "error" and is_kickable_error(stanza) then
607 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
608 return self:handle_kickable(origin, stanza); -- send unavailable
611 local o_data = self:get_occupant_by_nick(to);
613 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
616 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
617 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
618 stanza.attr.from = current_nick;
619 self:route_to_occupant(o_data, stanza)
620 -- TODO: Remove x tag?
621 stanza.attr.from = from;
625 function room_mt:send_form(origin, stanza)
626 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
627 :add_child(self:get_form_layout(stanza.attr.from):form())
631 function room_mt:get_form_layout(actor)
632 local form = dataform.new({
633 title = "Configuration for "..self.jid,
634 instructions = "Complete and submit this form to configure the room.",
638 value = 'http://jabber.org/protocol/muc#roomconfig'
641 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
644 function room_mt:process_form(origin, stanza)
645 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
646 if form.attr.type == "cancel" then
647 origin.send(st.reply(stanza));
648 elseif form.attr.type == "submit" then
649 local fields, errors, present;
650 if form.tags[1] == nil then -- Instant room
651 fields, present = {}, {};
653 fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
654 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
655 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
660 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
661 function event.update_option(name, field, allowed)
662 local new = fields[field];
663 if new == nil then return; end
664 if allowed and not allowed[new] then return; end
665 if new == self["get_"..name](self) then return; end
666 event.status_codes["104"] = true;
667 self["set_"..name](self, new);
670 module:fire_event("muc-config-submitted", event);
671 for submitted_field in pairs(present) do
672 event.field, event.value = submitted_field, fields[submitted_field];
673 module:fire_event("muc-config-submitted/"..submitted_field, event);
675 event.field, event.value = nil, nil;
677 if self.save then self:save(true); end
678 origin.send(st.reply(stanza));
680 if next(event.status_codes) then
681 local msg = st.message({type='groupchat', from=self.jid})
682 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
683 for code in pairs(event.status_codes) do
684 msg:tag("status", {code = code;}):up();
687 self:broadcast_message(msg);
690 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
695 -- Removes everyone from the room
696 function room_mt:clear(x)
697 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
698 local occupants_updated = {};
699 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
701 self:save_occupant(occupant);
702 occupants_updated[occupant] = true;
704 for occupant in pairs(occupants_updated) do
705 self:publicise_occupant_status(occupant, x);
706 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
710 function room_mt:destroy(newjid, reason, password)
711 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
712 :tag("item", { affiliation='none', role='none' }):up()
713 :tag("destroy", {jid=newjid});
714 if reason then x:tag("reason"):text(reason):up(); end
715 if password then x:tag("password"):text(password):up(); end
718 module:fire_event("muc-room-destroyed", { room = self });
721 function room_mt:handle_disco_info_get_query(origin, stanza)
722 origin.send(self:get_disco_info(stanza));
726 function room_mt:handle_disco_items_get_query(origin, stanza)
727 origin.send(self:get_disco_items(stanza));
731 function room_mt:handle_admin_query_set_command(origin, stanza)
732 local item = stanza.tags[1].tags[1];
734 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
736 if item.attr.jid then -- Validate provided JID
737 item.attr.jid = jid_prep(item.attr.jid);
738 if not item.attr.jid then
739 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
743 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
744 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
745 if occupant then item.attr.jid = occupant.jid; end
746 elseif not item.attr.nick and item.attr.jid then
747 local nick = self:get_occupant_jid(item.attr.jid);
748 if nick then item.attr.nick = select(3, jid_split(nick)); end
750 local actor = stanza.attr.from;
751 local reason = item:get_child_text("reason");
752 local success, errtype, err
753 if item.attr.affiliation and item.attr.jid and not item.attr.role then
754 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
755 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
756 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
758 success, errtype, err = nil, "cancel", "bad-request";
761 origin.send(st.error_reply(stanza, errtype, err));
763 origin.send(st.reply(stanza));
768 function room_mt:handle_admin_query_get_command(origin, stanza)
769 local actor = stanza.attr.from;
770 local affiliation = self:get_affiliation(actor);
771 local item = stanza.tags[1].tags[1];
772 local _aff = item.attr.affiliation;
773 local _aff_rank = valid_affiliations[_aff or "none"];
774 local _rol = item.attr.role;
775 if _aff and _aff_rank and not _rol then
776 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
777 -- e.g. an admin can't ask for a list of owners
778 local affiliation_rank = valid_affiliations[affiliation or "none"];
779 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
780 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
781 for jid in self:each_affiliation(_aff or "none") do
782 reply:tag("item", {affiliation = _aff, jid = jid}):up();
784 origin.send(reply:up());
787 origin.send(st.error_reply(stanza, "auth", "forbidden"));
790 elseif _rol and valid_roles[_rol or "none"] and not _aff then
791 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
792 if valid_roles[role or "none"] >= valid_roles.moderator then
793 if _rol == "none" then _rol = nil; end
794 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
795 -- TODO: whois check here? (though fully anonymous rooms are not supported)
796 for occupant_jid, occupant in self:each_occupant() do
797 if occupant.role == _rol then
798 local nick = select(3,jid_split(occupant_jid));
799 self:build_item_list(occupant, reply, false, nick);
802 origin.send(reply:up());
805 origin.send(st.error_reply(stanza, "auth", "forbidden"));
809 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
814 function room_mt:handle_owner_query_get_to_room(origin, stanza)
815 if self:get_affiliation(stanza.attr.from) ~= "owner" then
816 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
820 self:send_form(origin, stanza);
823 function room_mt:handle_owner_query_set_to_room(origin, stanza)
824 if self:get_affiliation(stanza.attr.from) ~= "owner" then
825 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
829 local child = stanza.tags[1].tags[1];
831 origin.send(st.error_reply(stanza, "modify", "bad-request"));
833 elseif child.name == "destroy" then
834 local newjid = child.attr.jid;
835 local reason = child:get_child_text("reason");
836 local password = child:get_child_text("password");
837 self:destroy(newjid, reason, password);
838 origin.send(st.reply(stanza));
840 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
841 return self:process_form(origin, stanza);
843 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
848 function room_mt:handle_groupchat_to_room(origin, stanza)
849 local from = stanza.attr.from;
850 local occupant = self:get_occupant_by_real_jid(from);
851 if module:fire_event("muc-occupant-groupchat", {
852 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
853 }) then return true; end
854 stanza.attr.from = occupant.nick;
855 self:broadcast_message(stanza);
856 stanza.attr.from = from;
861 module:hook("muc-occupant-groupchat", function(event)
862 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
863 if role_rank <= valid_roles.none then
864 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
866 elseif role_rank <= valid_roles.visitor then
867 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
872 -- hack - some buggy clients send presence updates to the room rather than their nick
873 function room_mt:handle_presence_to_room(origin, stanza)
874 local current_nick = self:get_occupant_jid(stanza.attr.from);
877 local to = stanza.attr.to;
878 stanza.attr.to = current_nick;
879 handled = self:handle_presence_to_occupant(origin, stanza);
885 -- Need visitor role or higher to invite
886 module:hook("muc-pre-invite", function(event)
887 local room, stanza = event.room, event.stanza;
888 local _from = stanza.attr.from;
889 local inviter = room:get_occupant_by_real_jid(_from);
890 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
891 if valid_roles[role or "none"] <= valid_roles.visitor then
892 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
897 function room_mt:handle_mediated_invite(origin, stanza)
898 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
899 local invitee = jid_prep(payload.attr.to);
901 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
903 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
906 local invite = muc_util.filter_muc_x(st.clone(stanza));
907 invite.attr.from = self.jid;
908 invite.attr.to = invitee;
909 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
910 :tag('invite', {from = stanza.attr.from;})
911 :tag('reason'):text(payload:get_child_text("reason")):up()
914 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
915 self:route_stanza(invite);
920 -- COMPAT: Some older clients expect this
921 module:hook("muc-invite", function(event)
922 local room, stanza = event.room, event.stanza;
923 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
924 local reason = invite:get_child_text("reason");
925 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
930 -- Add a plain message for clients which don't support invites
931 module:hook("muc-invite", function(event)
932 local room, stanza = event.room, event.stanza;
933 if not stanza:get_child("body") then
934 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
935 local reason = invite:get_child_text("reason") or "";
937 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
942 function room_mt:handle_mediated_decline(origin, stanza)
943 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
944 local declinee = jid_prep(payload.attr.to);
946 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
948 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
951 local decline = muc_util.filter_muc_x(st.clone(stanza));
952 decline.attr.from = self.jid;
953 decline.attr.to = declinee;
954 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
955 :tag("decline", {from = stanza.attr.from})
956 :tag("reason"):text(payload:get_child_text("reason")):up()
959 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
960 declinee = decline.attr.to; -- re-fetch, in case event modified it
962 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
963 occupant = self:get_occupant_by_nick(declinee);
966 self:route_to_occupant(occupant, decline);
968 self:route_stanza(decline);
974 -- Add a plain message for clients which don't support declines
975 module:hook("muc-decline", function(event)
976 local room, stanza = event.room, event.stanza;
977 if not stanza:get_child("body") then
978 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
979 local reason = decline:get_child_text("reason") or "";
981 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
986 function room_mt:handle_message_to_room(origin, stanza)
987 local type = stanza.attr.type;
988 if type == "groupchat" then
989 return self:handle_groupchat_to_room(origin, stanza)
990 elseif type == "error" and is_kickable_error(stanza) then
991 return self:handle_kickable(origin, stanza)
992 elseif type == nil then
993 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
995 local payload = x.tags[1];
996 if payload == nil then --luacheck: ignore 542
998 elseif payload.name == "invite" and payload.attr.to then
999 return self:handle_mediated_invite(origin, stanza)
1000 elseif payload.name == "decline" and payload.attr.to then
1001 return self:handle_mediated_decline(origin, stanza)
1003 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1009 function room_mt:route_stanza(stanza) -- luacheck: ignore 212
1010 module:send(stanza);
1013 function room_mt:get_affiliation(jid)
1014 local node, host, resource = jid_split(jid);
1015 local bare = node and node.."@"..host or host;
1016 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1017 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1021 -- Iterates over jid, affiliation pairs
1022 function room_mt:each_affiliation(with_affiliation)
1023 if not with_affiliation then
1024 return pairs(self._affiliations);
1026 return function(_affiliations, jid)
1028 repeat -- Iterate until we get a match
1029 jid, affiliation = next(_affiliations, jid);
1030 until jid == nil or affiliation == with_affiliation
1031 return jid, affiliation;
1032 end, self._affiliations, nil
1036 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1037 if not actor then return nil, "modify", "not-acceptable"; end;
1039 local node, host, resource = jid_split(jid);
1040 if not host then return nil, "modify", "not-acceptable"; end
1041 jid = jid_join(node, host); -- Bare
1042 local is_host_only = node == nil;
1044 if valid_affiliations[affiliation or "none"] == nil then
1045 return nil, "modify", "not-acceptable";
1047 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1049 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1050 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1052 if actor == true then
1053 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1055 local actor_affiliation = self:get_affiliation(actor);
1056 if actor_affiliation == "owner" then
1057 if jid_bare(actor) == jid then -- self change
1058 -- need at least one owner
1059 local is_last = true;
1060 for j in self:each_affiliation("owner") do
1061 if j ~= jid then is_last = false; break; end
1064 return nil, "cancel", "conflict";
1067 -- owners can do anything else
1068 elseif affiliation == "owner" or affiliation == "admin"
1069 or actor_affiliation ~= "admin"
1070 or target_affiliation == "owner" or target_affiliation == "admin" then
1071 -- Can't demote owners or other admins
1072 return nil, "cancel", "not-allowed";
1076 -- Set in 'database'
1077 self._affiliations[jid] = affiliation;
1080 local role = self:get_default_role(affiliation);
1081 local role_rank = valid_roles[role or "none"];
1082 local occupants_updated = {}; -- Filled with old roles
1083 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
1084 if occupant.bare_jid == jid or (
1085 -- Outcast can be by host.
1086 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1088 -- need to publcize in all cases; as affiliation in <item/> has changed.
1089 occupants_updated[occupant] = occupant.role;
1090 if occupant.role ~= role and (
1092 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1094 occupant.role = role;
1095 self:save_occupant(occupant);
1100 -- Tell the room of the new occupant affiliations+roles
1101 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1102 if not role then -- getting kicked
1103 if affiliation == "outcast" then
1104 x:tag("status", {code="301"}):up(); -- banned
1106 x:tag("status", {code="321"}):up(); -- affiliation change
1109 local is_semi_anonymous = self:get_whois() == "moderators";
1110 for occupant, old_role in pairs(occupants_updated) do
1111 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1112 if occupant.role == nil then
1113 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1114 elseif is_semi_anonymous and
1115 (old_role == "moderator" and occupant.role ~= "moderator") or
1116 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1117 -- Send everyone else's presences (as jid visibility has changed)
1118 for real_jid in occupant:each_session() do
1119 self:send_occupant_list(real_jid, function(occupant_jid, occupant) --luacheck: ignore 212 433
1120 return occupant.bare_jid ~= jid;
1126 if self.save then self:save(); end
1128 module:fire_event("muc-set-affiliation", {
1132 affiliation = affiliation or "none";
1134 previous_affiliation = target_affiliation;
1135 in_room = next(occupants_updated) ~= nil;
1141 function room_mt:get_role(nick)
1142 local occupant = self:get_occupant_by_nick(nick);
1143 return occupant and occupant.role or nil;
1146 function room_mt:set_role(actor, occupant_jid, role, reason)
1147 if not actor then return nil, "modify", "not-acceptable"; end
1149 local occupant = self:get_occupant_by_nick(occupant_jid);
1150 if not occupant then return nil, "modify", "not-acceptable"; end
1152 if valid_roles[role or "none"] == nil then
1153 return nil, "modify", "not-acceptable";
1155 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1157 if actor == true then
1158 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1160 -- Can't do anything to other owners or admins
1161 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1162 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1163 return nil, "cancel", "not-allowed";
1166 -- If you are trying to give or take moderator role you need to be an owner or admin
1167 if occupant.role == "moderator" or role == "moderator" then
1168 local actor_affiliation = self:get_affiliation(actor);
1169 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1170 return nil, "cancel", "not-allowed";
1174 -- Need to be in the room and a moderator
1175 local actor_occupant = self:get_occupant_by_real_jid(actor);
1176 if not actor_occupant or actor_occupant.role ~= "moderator" then
1177 return nil, "cancel", "not-allowed";
1181 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1183 x:tag("status", {code = "307"}):up();
1185 occupant.role = role;
1186 self:save_occupant(occupant);
1187 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1189 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1194 local whois = module:require "muc/whois";
1195 room_mt.get_whois = whois.get;
1196 room_mt.set_whois = whois.set;
1198 local _M = {}; -- module "muc"
1200 function _M.new_room(jid, config) -- luacheck: ignore 212
1202 return setmetatable({
1212 _M.room_mt = room_mt;