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:get_occupant_jid(real_jid)
40 return self._jid_nick[real_jid]
43 function room_mt:get_default_role(affiliation)
44 local role = module:fire_event("muc-get-default-role", {
46 affiliation = affiliation;
47 affiliation_rank = valid_affiliations[affiliation or "none"];
49 return role, valid_roles[role or "none"];
51 module:hook("muc-get-default-role", function(event)
52 if event.affiliation_rank >= valid_affiliations.admin then
54 elseif event.affiliation_rank >= valid_affiliations.none then
59 --- Occupant functions
60 function room_mt:new_occupant(bare_real_jid, nick)
61 local occupant = occupant_lib.new(bare_real_jid, nick);
62 local affiliation = self:get_affiliation(bare_real_jid);
63 occupant.role = self:get_default_role(affiliation);
67 function room_mt:get_occupant_by_nick(nick)
68 local occupant = self._occupants[nick];
69 if occupant == nil then return nil end
70 return occupant_lib.copy(occupant);
74 local function next_copied_occupant(occupants, occupant_jid)
75 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
76 if next_occupant_jid == nil then return nil end
77 return next_occupant_jid, occupant_lib.copy(raw_occupant);
79 -- FIXME Explain what 'read_only' is supposed to be
80 function room_mt:each_occupant(read_only) -- luacheck: ignore 212
81 return next_copied_occupant, self._occupants, nil;
85 function room_mt:has_occupant()
86 return next(self._occupants, nil) ~= nil
89 function room_mt:get_occupant_by_real_jid(real_jid)
90 local occupant_jid = self:get_occupant_jid(real_jid);
91 if occupant_jid == nil then return nil end
92 return self:get_occupant_by_nick(occupant_jid);
95 function room_mt:save_occupant(occupant)
96 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
97 local id = occupant.nick
99 -- Need to maintain _jid_nick secondary index
100 local old_occupant = self._occupants[id];
102 for real_jid in old_occupant:each_session() do
103 self._jid_nick[real_jid] = nil;
107 local has_live_session = false
108 if occupant.role ~= nil then
109 for real_jid, presence in occupant:each_session() do
110 if presence.attr.type == nil then
111 has_live_session = true
112 self._jid_nick[real_jid] = occupant.nick;
115 if not has_live_session then
116 -- Has no live sessions left; they have left the room.
120 if not has_live_session then
123 self._occupants[id] = occupant
126 function room_mt:route_to_occupant(occupant, stanza)
127 local to = stanza.attr.to;
128 for jid in occupant:each_session() do
129 stanza.attr.to = jid;
130 self:route_stanza(stanza);
135 -- actor is the attribute table
136 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
137 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
138 if actor_nick or actor_jid then
139 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
142 x:tag("reason"):text(reason):up()
148 -- actor is (real) jid
149 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
150 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
151 local role = occupant.role or "none";
153 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
155 for real_jid in occupant:each_session() do
156 add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
162 function room_mt:broadcast_message(stanza)
163 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
166 self:broadcast(stanza);
170 -- Broadcast a stanza to all occupants in the room.
171 -- optionally checks conditional called with (nick, occupant)
172 function room_mt:broadcast(stanza, cond_func)
173 for nick, occupant in self:each_occupant() do
174 if cond_func == nil or cond_func(nick, occupant) then
175 self:route_to_occupant(occupant, stanza)
180 local function can_see_real_jids(whois, occupant)
181 if whois == "anyone" then
183 elseif whois == "moderators" then
184 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
188 -- Broadcasts an occupant's presence to the whole room
189 -- Takes the x element that goes into the stanzas
190 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
191 -- Build real jid and (optionally) occupant jid template presences
192 local base_presence do
193 -- Try to use main jid's presence
194 local pr = occupant:get_presence();
195 if pr and (pr.attr.type ~= "unavailable" or occupant.role == nil) then
196 base_presence = st.clone(pr);
197 else -- user is leaving but didn't send a leave presence. make one for them
198 base_presence = st.presence {from = occupant.nick; type = "unavailable";};
202 -- Fire event (before full_p and anon_p are created)
204 room = self; stanza = base_presence; x = base_x;
205 occupant = occupant; nick = nick; actor = actor;
208 module:fire_event("muc-broadcast-presence", event);
210 -- Allow muc-broadcast-presence listeners to change things
213 reason = event.reason;
215 local whois = self:get_whois();
219 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
222 local full_p, full_x;
223 local function get_full_p()
224 if full_p == nil then
225 full_x = st.clone(base_x);
226 self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
227 full_p = st.clone(base_presence):add_child(full_x);
229 return full_p, full_x;
232 local anon_p, anon_x;
233 local function get_anon_p()
234 if anon_p == nil then
235 anon_x = st.clone(base_x);
236 self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
237 anon_p = st.clone(base_presence):add_child(anon_x);
239 return anon_p, anon_x;
242 local self_p, self_x;
243 if can_see_real_jids(whois, occupant) then
244 self_p, self_x = get_full_p();
246 -- Can always see your own full jids
247 -- But not allowed to see actor's
248 self_x = st.clone(base_x);
249 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
250 self_p = st.clone(base_presence):add_child(self_x);
254 for occupant_nick, n_occupant in self:each_occupant() do
255 if occupant_nick ~= occupant.nick then
257 if can_see_real_jids(whois, n_occupant) then
259 elseif occupant.bare_jid == n_occupant.bare_jid then
264 self:route_to_occupant(n_occupant, pr);
268 -- Presences for occupant itself
269 self_x:tag("status", {code = "110";}):up();
270 if occupant.role == nil then
271 -- They get an unavailable
272 self:route_to_occupant(occupant, self_p);
274 -- use their own presences as templates
275 for full_jid, pr in occupant:each_session() do
277 pr.attr.to = full_jid;
278 pr:add_child(self_x);
279 self:route_stanza(pr);
284 function room_mt:send_occupant_list(to, filter)
285 local to_bare = jid_bare(to);
286 local is_anonymous = false;
287 local whois = self:get_whois();
288 if whois ~= "anyone" then
289 local affiliation = self:get_affiliation(to);
290 if affiliation ~= "admin" and affiliation ~= "owner" then
291 local occupant = self:get_occupant_by_real_jid(to);
292 if not (occupant and can_see_real_jids(whois, occupant)) then
297 for occupant_jid, occupant in self:each_occupant() do
298 if filter == nil or filter(occupant_jid, occupant) then
299 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
300 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
301 local pres = st.clone(occupant:get_presence());
304 self:route_stanza(pres);
309 function room_mt:get_disco_info(stanza)
310 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
311 local form = dataform.new {
312 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
315 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form, formdata = formdata ;});
316 reply:add_child(form:form(formdata, "result"));
319 module:hook("muc-disco#info", function(event)
320 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
322 module:hook("muc-disco#info", function(event)
323 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants" });
324 event.formdata["muc#roominfo_occupants"] = tostring(iterators.count(event.room:each_occupant()));
327 function room_mt:get_disco_items(stanza)
328 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
329 for room_jid in self:each_occupant() do
330 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
335 function room_mt:handle_kickable(origin, stanza) -- luacheck: ignore 212
336 local real_jid = stanza.attr.from;
337 local occupant = self:get_occupant_by_real_jid(real_jid);
338 if occupant == nil then return nil; end
339 local type, condition, text = stanza:get_error();
340 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
342 error_message = error_message..": "..text;
344 occupant:set_session(real_jid, st.presence({type="unavailable"})
345 :tag('status'):text(error_message));
346 self:save_occupant(occupant);
347 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
348 :tag("status", {code = "307"})
349 self:publicise_occupant_status(occupant, x);
350 if occupant.jid == real_jid then -- Was last session
351 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
356 -- Give the room creator owner affiliation
357 module:hook("muc-room-pre-create", function(event)
358 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
361 -- check if user is banned
362 module:hook("muc-occupant-pre-join", function(event)
363 local room, stanza = event.room, event.stanza;
364 local affiliation = room:get_affiliation(stanza.attr.from);
365 if affiliation == "outcast" then
366 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
367 reply.tags[1].attr.code = "403";
368 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
373 function room_mt:handle_presence_to_occupant(origin, stanza)
374 local type = stanza.attr.type;
375 if type == "error" then -- error, kick em out!
376 return self:handle_kickable(origin, stanza)
377 elseif type == nil or type == "unavailable" then
378 local real_jid = stanza.attr.from;
379 local bare_jid = jid_bare(real_jid);
380 local orig_occupant, dest_occupant;
381 local is_new_room = next(self._affiliations) == nil;
383 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
384 if module:fire_event("muc-room-pre-create", {
388 }) then return true; end
390 orig_occupant = self:get_occupant_by_real_jid(real_jid);
391 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
393 local is_first_dest_session;
394 if type == "unavailable" then -- luacheck: ignore 542
395 -- FIXME Why the empty if branch?
396 -- dest_occupant = nil
397 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
398 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
399 dest_occupant = orig_occupant;
401 local dest_jid = stanza.attr.to;
402 dest_occupant = self:get_occupant_by_nick(dest_jid);
403 if dest_occupant == nil then
404 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
405 is_first_dest_session = true;
406 dest_occupant = self:new_occupant(bare_jid, dest_jid);
408 is_first_dest_session = false;
411 local is_last_orig_session;
412 if orig_occupant ~= nil then
413 -- Is there are least 2 sessions?
414 local iter, ob, last = orig_occupant:each_session();
415 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
418 local event, event_name = {
422 is_first_session = is_first_dest_session;
423 is_last_session = is_last_orig_session;
425 if orig_occupant == nil then
426 event_name = "muc-occupant-pre-join";
427 event.is_new_room = is_new_room;
428 event.occupant = dest_occupant;
429 elseif dest_occupant == nil then
430 event_name = "muc-occupant-pre-leave";
431 event.occupant = orig_occupant;
433 event_name = "muc-occupant-pre-change";
434 event.orig_occupant = orig_occupant;
435 event.dest_occupant = dest_occupant;
437 if module:fire_event(event_name, event) then return true; end
439 -- Check for nick conflicts
440 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
441 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
442 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
443 reply.tags[1].attr.code = "409";
444 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
448 -- Send presence stanza about original occupant
449 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
450 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
452 if dest_occupant == nil then -- Session is leaving
453 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
454 if is_last_orig_session then
455 orig_occupant.role = nil;
457 orig_occupant:set_session(real_jid, stanza);
459 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
460 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
461 orig_occupant:set_session(real_jid, generated_unavail);
462 dest_nick = select(3, jid_split(dest_occupant.nick));
463 if not is_first_dest_session then -- User is swapping into another pre-existing session
464 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
465 -- Show the other session leaving
466 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
467 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
468 add_item(x, self:get_affiliation(bare_jid), "none");
469 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
471 self:route_stanza(pr);
473 if is_first_dest_session and is_last_orig_session then -- Normal nick change
474 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
475 orig_x:tag("status", {code = "303";}):up();
476 else -- The session itself always needs to see a nick change
477 -- don't want to get our old nick's available presence,
478 -- so remove our session from there, and manually generate an unavailable
479 orig_occupant:remove_session(real_jid);
480 log("debug", "generating nick change for %s", real_jid);
481 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
482 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
483 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
484 x:tag("status", {code = "303";}):up();
485 x:tag("status", {code = "110";}):up();
486 self:route_stanza(generated_unavail:add_child(x));
487 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
490 self:save_occupant(orig_occupant);
491 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
493 if is_last_orig_session then
494 module:fire_event("muc-occupant-left", {
496 nick = orig_occupant.nick;
497 occupant = orig_occupant;
502 if dest_occupant ~= nil then
503 dest_occupant:set_session(real_jid, stanza);
504 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
506 dest_x:tag("status", {code = "201"}):up();
508 if orig_occupant == nil and self:get_whois() == "anyone" then
509 dest_x:tag("status", {code = "100"}):up();
511 self:save_occupant(dest_occupant);
513 if orig_occupant == nil then
514 -- Send occupant list to newly joined user
515 self:send_occupant_list(real_jid, function(nick, occupant) -- luacheck: ignore 212
516 -- Don't include self
517 return occupant:get_presence(real_jid) == nil;
520 self:publicise_occupant_status(dest_occupant, dest_x);
522 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
523 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
524 -- Show the original nick joining again
525 local pr = st.clone(orig_occupant:get_presence());
526 pr.attr.to = real_jid;
527 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
528 self:build_item_list(orig_occupant, x, false);
529 -- TODO: new status code to inform client this was the multi-session it left?
531 self:route_stanza(pr);
534 if orig_occupant == nil then
535 if is_first_dest_session then
536 module:fire_event("muc-occupant-joined", {
538 nick = dest_occupant.nick;
539 occupant = dest_occupant;
542 module:fire_event("muc-occupant-session-new", {
544 nick = dest_occupant.nick;
545 occupant = dest_occupant;
552 elseif type ~= 'result' then -- bad type
553 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
554 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
560 function room_mt:handle_iq_to_occupant(origin, stanza)
561 local from, to = stanza.attr.from, stanza.attr.to;
562 local type = stanza.attr.type;
563 local id = stanza.attr.id;
564 local occupant = self:get_occupant_by_nick(to);
565 if (type == "error" or type == "result") then
566 do -- deconstruct_stanza_id
567 if not occupant then return nil; end
568 local from_jid, orig_id, to_jid_hash = (base64.decode(id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
569 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
570 local from_occupant_jid = self:get_occupant_jid(from_jid);
571 if from_occupant_jid == nil then return nil; end
573 for to_jid in occupant:each_session() do
574 if md5(to_jid) == to_jid_hash then
575 session_jid = to_jid;
579 if session_jid == nil then return nil; end
580 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, orig_id;
582 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
583 self:route_stanza(stanza);
584 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
586 else -- Type is "get" or "set"
587 local current_nick = self:get_occupant_jid(from);
588 if not current_nick then
589 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
592 if not occupant then -- recipient not in room
593 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
596 do -- construct_stanza_id
597 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
599 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
600 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
601 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
602 stanza.attr.to = jid_bare(stanza.attr.to);
604 self:route_stanza(stanza);
605 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
610 function room_mt:handle_message_to_occupant(origin, stanza)
611 local from, to = stanza.attr.from, stanza.attr.to;
612 local current_nick = self:get_occupant_jid(from);
613 local type = stanza.attr.type;
614 if not current_nick then -- not in room
615 if type ~= "error" then
616 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
620 if type == "groupchat" then -- groupchat messages not allowed in PM
621 origin.send(st.error_reply(stanza, "modify", "bad-request"));
623 elseif type == "error" and is_kickable_error(stanza) then
624 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
625 return self:handle_kickable(origin, stanza); -- send unavailable
628 local o_data = self:get_occupant_by_nick(to);
630 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
633 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
634 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
635 stanza.attr.from = current_nick;
636 self:route_to_occupant(o_data, stanza)
637 -- TODO: Remove x tag?
638 stanza.attr.from = from;
642 function room_mt:send_form(origin, stanza)
643 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
644 :add_child(self:get_form_layout(stanza.attr.from):form())
648 function room_mt:get_form_layout(actor)
649 local form = dataform.new({
650 title = "Configuration for "..self.jid,
651 instructions = "Complete and submit this form to configure the room.",
655 value = 'http://jabber.org/protocol/muc#roomconfig'
658 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
661 function room_mt:process_form(origin, stanza)
662 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
663 if form.attr.type == "cancel" then
664 origin.send(st.reply(stanza));
665 elseif form.attr.type == "submit" then
666 local fields, errors, present;
667 if form.tags[1] == nil then -- Instant room
668 fields, present = {}, {};
670 fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
671 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
672 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
677 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
678 function event.update_option(name, field, allowed)
679 local new = fields[field];
680 if new == nil then return; end
681 if allowed and not allowed[new] then return; end
682 if new == self["get_"..name](self) then return; end
683 event.status_codes["104"] = true;
684 self["set_"..name](self, new);
687 module:fire_event("muc-config-submitted", event);
688 for submitted_field in pairs(present) do
689 event.field, event.value = submitted_field, fields[submitted_field];
690 module:fire_event("muc-config-submitted/"..submitted_field, event);
692 event.field, event.value = nil, nil;
694 if self.save then self:save(true); end
695 origin.send(st.reply(stanza));
697 if next(event.status_codes) then
698 local msg = st.message({type='groupchat', from=self.jid})
699 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
700 for code in pairs(event.status_codes) do
701 msg:tag("status", {code = code;}):up();
704 self:broadcast_message(msg);
707 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
712 -- Removes everyone from the room
713 function room_mt:clear(x)
714 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
715 local occupants_updated = {};
716 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
718 self:save_occupant(occupant);
719 occupants_updated[occupant] = true;
721 for occupant in pairs(occupants_updated) do
722 self:publicise_occupant_status(occupant, x);
723 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
727 function room_mt:destroy(newjid, reason, password)
728 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
729 :tag("item", { affiliation='none', role='none' }):up()
730 :tag("destroy", {jid=newjid});
731 if reason then x:tag("reason"):text(reason):up(); end
732 if password then x:tag("password"):text(password):up(); end
735 module:fire_event("muc-room-destroyed", { room = self });
738 function room_mt:handle_disco_info_get_query(origin, stanza)
739 origin.send(self:get_disco_info(stanza));
743 function room_mt:handle_disco_items_get_query(origin, stanza)
744 origin.send(self:get_disco_items(stanza));
748 function room_mt:handle_admin_query_set_command(origin, stanza)
749 local item = stanza.tags[1].tags[1];
751 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
753 if item.attr.jid then -- Validate provided JID
754 item.attr.jid = jid_prep(item.attr.jid);
755 if not item.attr.jid then
756 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
760 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
761 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
762 if occupant then item.attr.jid = occupant.jid; end
763 elseif not item.attr.nick and item.attr.jid then
764 local nick = self:get_occupant_jid(item.attr.jid);
765 if nick then item.attr.nick = select(3, jid_split(nick)); end
767 local actor = stanza.attr.from;
768 local reason = item:get_child_text("reason");
769 local success, errtype, err
770 if item.attr.affiliation and item.attr.jid and not item.attr.role then
771 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
772 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
773 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
775 success, errtype, err = nil, "cancel", "bad-request";
778 origin.send(st.error_reply(stanza, errtype, err));
780 origin.send(st.reply(stanza));
785 function room_mt:handle_admin_query_get_command(origin, stanza)
786 local actor = stanza.attr.from;
787 local affiliation = self:get_affiliation(actor);
788 local item = stanza.tags[1].tags[1];
789 local _aff = item.attr.affiliation;
790 local _aff_rank = valid_affiliations[_aff or "none"];
791 local _rol = item.attr.role;
792 if _aff and _aff_rank and not _rol then
793 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
794 -- e.g. an admin can't ask for a list of owners
795 local affiliation_rank = valid_affiliations[affiliation or "none"];
796 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
797 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
798 for jid in self:each_affiliation(_aff or "none") do
799 reply:tag("item", {affiliation = _aff, jid = jid}):up();
801 origin.send(reply:up());
804 origin.send(st.error_reply(stanza, "auth", "forbidden"));
807 elseif _rol and valid_roles[_rol or "none"] and not _aff then
808 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
809 if valid_roles[role or "none"] >= valid_roles.moderator then
810 if _rol == "none" then _rol = nil; end
811 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
812 -- TODO: whois check here? (though fully anonymous rooms are not supported)
813 for occupant_jid, occupant in self:each_occupant() do
814 if occupant.role == _rol then
815 local nick = select(3,jid_split(occupant_jid));
816 self:build_item_list(occupant, reply, false, nick);
819 origin.send(reply:up());
822 origin.send(st.error_reply(stanza, "auth", "forbidden"));
826 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
831 function room_mt:handle_owner_query_get_to_room(origin, stanza)
832 if self:get_affiliation(stanza.attr.from) ~= "owner" then
833 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
837 self:send_form(origin, stanza);
840 function room_mt:handle_owner_query_set_to_room(origin, stanza)
841 if self:get_affiliation(stanza.attr.from) ~= "owner" then
842 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
846 local child = stanza.tags[1].tags[1];
848 origin.send(st.error_reply(stanza, "modify", "bad-request"));
850 elseif child.name == "destroy" then
851 local newjid = child.attr.jid;
852 local reason = child:get_child_text("reason");
853 local password = child:get_child_text("password");
854 self:destroy(newjid, reason, password);
855 origin.send(st.reply(stanza));
857 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
858 return self:process_form(origin, stanza);
860 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
865 function room_mt:handle_groupchat_to_room(origin, stanza)
866 local from = stanza.attr.from;
867 local occupant = self:get_occupant_by_real_jid(from);
868 if module:fire_event("muc-occupant-groupchat", {
869 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
870 }) then return true; end
871 stanza.attr.from = occupant.nick;
872 self:broadcast_message(stanza);
873 stanza.attr.from = from;
878 module:hook("muc-occupant-groupchat", function(event)
879 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
880 if role_rank <= valid_roles.none then
881 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
883 elseif role_rank <= valid_roles.visitor then
884 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
889 -- hack - some buggy clients send presence updates to the room rather than their nick
890 function room_mt:handle_presence_to_room(origin, stanza)
891 local current_nick = self:get_occupant_jid(stanza.attr.from);
894 local to = stanza.attr.to;
895 stanza.attr.to = current_nick;
896 handled = self:handle_presence_to_occupant(origin, stanza);
902 -- Need visitor role or higher to invite
903 module:hook("muc-pre-invite", function(event)
904 local room, stanza = event.room, event.stanza;
905 local _from = stanza.attr.from;
906 local inviter = room:get_occupant_by_real_jid(_from);
907 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
908 if valid_roles[role or "none"] <= valid_roles.visitor then
909 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
914 function room_mt:handle_mediated_invite(origin, stanza)
915 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
916 local invitee = jid_prep(payload.attr.to);
918 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
920 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
923 local invite = muc_util.filter_muc_x(st.clone(stanza));
924 invite.attr.from = self.jid;
925 invite.attr.to = invitee;
926 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
927 :tag('invite', {from = stanza.attr.from;})
928 :tag('reason'):text(payload:get_child_text("reason")):up()
931 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
932 self:route_stanza(invite);
937 -- COMPAT: Some older clients expect this
938 module:hook("muc-invite", function(event)
939 local room, stanza = event.room, event.stanza;
940 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
941 local reason = invite:get_child_text("reason");
942 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
947 -- Add a plain message for clients which don't support invites
948 module:hook("muc-invite", function(event)
949 local room, stanza = event.room, event.stanza;
950 if not stanza:get_child("body") then
951 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
952 local reason = invite:get_child_text("reason") or "";
954 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
959 function room_mt:handle_mediated_decline(origin, stanza)
960 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
961 local declinee = jid_prep(payload.attr.to);
963 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
965 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
968 local decline = muc_util.filter_muc_x(st.clone(stanza));
969 decline.attr.from = self.jid;
970 decline.attr.to = declinee;
971 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
972 :tag("decline", {from = stanza.attr.from})
973 :tag("reason"):text(payload:get_child_text("reason")):up()
976 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
977 declinee = decline.attr.to; -- re-fetch, in case event modified it
979 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
980 occupant = self:get_occupant_by_nick(declinee);
983 self:route_to_occupant(occupant, decline);
985 self:route_stanza(decline);
991 -- Add a plain message for clients which don't support declines
992 module:hook("muc-decline", function(event)
993 local room, stanza = event.room, event.stanza;
994 if not stanza:get_child("body") then
995 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
996 local reason = decline:get_child_text("reason") or "";
998 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
1003 function room_mt:handle_message_to_room(origin, stanza)
1004 local type = stanza.attr.type;
1005 if type == "groupchat" then
1006 return self:handle_groupchat_to_room(origin, stanza)
1007 elseif type == "error" and is_kickable_error(stanza) then
1008 return self:handle_kickable(origin, stanza)
1009 elseif type == nil then
1010 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1012 local payload = x.tags[1];
1013 if payload == nil then --luacheck: ignore 542
1015 elseif payload.name == "invite" and payload.attr.to then
1016 return self:handle_mediated_invite(origin, stanza)
1017 elseif payload.name == "decline" and payload.attr.to then
1018 return self:handle_mediated_decline(origin, stanza)
1020 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1026 function room_mt:route_stanza(stanza) -- luacheck: ignore 212
1027 module:send(stanza);
1030 function room_mt:get_affiliation(jid)
1031 local node, host, resource = jid_split(jid);
1032 local bare = node and node.."@"..host or host;
1033 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1034 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1038 -- Iterates over jid, affiliation pairs
1039 function room_mt:each_affiliation(with_affiliation)
1040 if not with_affiliation then
1041 return pairs(self._affiliations);
1043 return function(_affiliations, jid)
1045 repeat -- Iterate until we get a match
1046 jid, affiliation = next(_affiliations, jid);
1047 until jid == nil or affiliation == with_affiliation
1048 return jid, affiliation;
1049 end, self._affiliations, nil
1053 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1054 if not actor then return nil, "modify", "not-acceptable"; end;
1056 local node, host, resource = jid_split(jid);
1057 if not host then return nil, "modify", "not-acceptable"; end
1058 jid = jid_join(node, host); -- Bare
1059 local is_host_only = node == nil;
1061 if valid_affiliations[affiliation or "none"] == nil then
1062 return nil, "modify", "not-acceptable";
1064 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1066 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1067 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1069 if actor == true then
1070 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1072 local actor_affiliation = self:get_affiliation(actor);
1073 if actor_affiliation == "owner" then
1074 if jid_bare(actor) == jid then -- self change
1075 -- need at least one owner
1076 local is_last = true;
1077 for j in self:each_affiliation("owner") do
1078 if j ~= jid then is_last = false; break; end
1081 return nil, "cancel", "conflict";
1084 -- owners can do anything else
1085 elseif affiliation == "owner" or affiliation == "admin"
1086 or actor_affiliation ~= "admin"
1087 or target_affiliation == "owner" or target_affiliation == "admin" then
1088 -- Can't demote owners or other admins
1089 return nil, "cancel", "not-allowed";
1093 -- Set in 'database'
1094 self._affiliations[jid] = affiliation;
1097 local role = self:get_default_role(affiliation);
1098 local role_rank = valid_roles[role or "none"];
1099 local occupants_updated = {}; -- Filled with old roles
1100 for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
1101 if occupant.bare_jid == jid or (
1102 -- Outcast can be by host.
1103 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1105 -- need to publcize in all cases; as affiliation in <item/> has changed.
1106 occupants_updated[occupant] = occupant.role;
1107 if occupant.role ~= role and (
1109 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1111 occupant.role = role;
1112 self:save_occupant(occupant);
1117 -- Tell the room of the new occupant affiliations+roles
1118 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1119 if not role then -- getting kicked
1120 if affiliation == "outcast" then
1121 x:tag("status", {code="301"}):up(); -- banned
1123 x:tag("status", {code="321"}):up(); -- affiliation change
1126 local is_semi_anonymous = self:get_whois() == "moderators";
1127 for occupant, old_role in pairs(occupants_updated) do
1128 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1129 if occupant.role == nil then
1130 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1131 elseif is_semi_anonymous and
1132 (old_role == "moderator" and occupant.role ~= "moderator") or
1133 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1134 -- Send everyone else's presences (as jid visibility has changed)
1135 for real_jid in occupant:each_session() do
1136 self:send_occupant_list(real_jid, function(occupant_jid, occupant) --luacheck: ignore 212 433
1137 return occupant.bare_jid ~= jid;
1143 if self.save then self:save(); end
1145 module:fire_event("muc-set-affiliation", {
1149 affiliation = affiliation or "none";
1151 previous_affiliation = target_affiliation;
1152 in_room = next(occupants_updated) ~= nil;
1158 function room_mt:get_role(nick)
1159 local occupant = self:get_occupant_by_nick(nick);
1160 return occupant and occupant.role or nil;
1163 function room_mt:set_role(actor, occupant_jid, role, reason)
1164 if not actor then return nil, "modify", "not-acceptable"; end
1166 local occupant = self:get_occupant_by_nick(occupant_jid);
1167 if not occupant then return nil, "modify", "not-acceptable"; end
1169 if valid_roles[role or "none"] == nil then
1170 return nil, "modify", "not-acceptable";
1172 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1174 if actor == true then
1175 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1177 -- Can't do anything to other owners or admins
1178 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1179 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1180 return nil, "cancel", "not-allowed";
1183 -- If you are trying to give or take moderator role you need to be an owner or admin
1184 if occupant.role == "moderator" or role == "moderator" then
1185 local actor_affiliation = self:get_affiliation(actor);
1186 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1187 return nil, "cancel", "not-allowed";
1191 -- Need to be in the room and a moderator
1192 local actor_occupant = self:get_occupant_by_real_jid(actor);
1193 if not actor_occupant or actor_occupant.role ~= "moderator" then
1194 return nil, "cancel", "not-allowed";
1198 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1200 x:tag("status", {code = "307"}):up();
1202 occupant.role = role;
1203 self:save_occupant(occupant);
1204 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1206 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1211 local whois = module:require "muc/whois";
1212 room_mt.get_whois = whois.get;
1213 room_mt.set_whois = whois.set;
1215 local _M = {}; -- module "muc"
1217 function _M.new_room(jid, config) -- luacheck: ignore 212
1219 return setmetatable({
1229 _M.room_mt = room_mt;