2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- Copyright (C) 2014 Daurnimator
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
10 local select = select;
11 local pairs, ipairs = pairs, ipairs;
13 local setmetatable = setmetatable;
15 local dataform = require "util.dataforms";
16 local iterators = require "util.iterators";
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local jid_join = require "util.jid".join;
21 local st = require "util.stanza";
22 local log = require "util.logger".init("mod_muc");
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
26 local occupant_lib = module:require "muc/occupant"
27 local muc_util = module:require "muc/util";
28 local is_kickable_error = muc_util.is_kickable_error;
29 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
32 room_mt.__index = room_mt;
34 function room_mt:__tostring()
35 return "MUC room ("..self.jid..")";
38 function room_mt:get_occupant_jid(real_jid)
39 return self._jid_nick[real_jid]
42 function room_mt:get_default_role(affiliation)
43 local role = module:fire_event("muc-get-default-role", {
45 affiliation = affiliation;
46 affiliation_rank = valid_affiliations[affiliation or "none"];
48 return role, valid_roles[role or "none"];
50 module:hook("muc-get-default-role", function(event)
51 if event.affiliation_rank >= valid_affiliations.admin then
53 elseif event.affiliation_rank >= valid_affiliations.none then
58 --- Occupant functions
59 function room_mt:new_occupant(bare_real_jid, nick)
60 local occupant = occupant_lib.new(bare_real_jid, nick);
61 local affiliation = self:get_affiliation(bare_real_jid);
62 occupant.role = self:get_default_role(affiliation);
66 function room_mt:get_occupant_by_nick(nick)
67 local occupant = self._occupants[nick];
68 if occupant == nil then return nil end
69 return occupant_lib.copy(occupant);
73 local function next_copied_occupant(occupants, occupant_jid)
74 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
75 if next_occupant_jid == nil then return nil end
76 return next_occupant_jid, occupant_lib.copy(raw_occupant);
78 function room_mt:each_occupant(read_only)
79 return next_copied_occupant, self._occupants, nil;
83 function room_mt:has_occupant()
84 return next(self._occupants, nil) ~= nil
87 function room_mt:get_occupant_by_real_jid(real_jid)
88 local occupant_jid = self:get_occupant_jid(real_jid);
89 if occupant_jid == nil then return nil end
90 return self:get_occupant_by_nick(occupant_jid);
93 function room_mt:save_occupant(occupant)
94 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
95 local id = occupant.nick
97 -- Need to maintain _jid_nick secondary index
98 local old_occupant = self._occupants[id];
100 for real_jid in old_occupant:each_session() do
101 self._jid_nick[real_jid] = nil;
105 local has_live_session = false
106 if occupant.role ~= nil then
107 for real_jid, presence in occupant:each_session() do
108 if presence.attr.type == nil then
109 has_live_session = true
110 self._jid_nick[real_jid] = occupant.nick;
113 if not has_live_session then
114 -- Has no live sessions left; they have left the room.
118 if not has_live_session then
121 self._occupants[id] = occupant
124 function room_mt:route_to_occupant(occupant, stanza)
125 local to = stanza.attr.to;
126 for jid, pr in occupant:each_session() do
127 stanza.attr.to = jid;
128 self:route_stanza(stanza);
133 -- actor is the attribute table
134 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
135 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
136 if actor_nick or actor_jid then
137 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
140 x:tag("reason"):text(reason):up()
146 -- actor is (real) jid
147 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
148 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
149 local role = occupant.role or "none";
151 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
153 for real_jid, session in occupant:each_session() do
154 add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
160 function room_mt:broadcast_message(stanza)
161 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
164 self:broadcast(stanza);
168 -- Broadcast a stanza to all occupants in the room.
169 -- optionally checks conditional called with (nick, occupant)
170 function room_mt:broadcast(stanza, cond_func)
171 for nick, occupant in self:each_occupant() do
172 if cond_func == nil or cond_func(nick, occupant) then
173 self:route_to_occupant(occupant, stanza)
178 local function can_see_real_jids(whois, occupant)
179 if whois == "anyone" then
181 elseif whois == "moderators" then
182 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
186 -- Broadcasts an occupant's presence to the whole room
187 -- Takes the x element that goes into the stanzas
188 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
189 -- Build real jid and (optionally) occupant jid template presences
190 local base_presence do
191 -- Try to use main jid's presence
192 local pr = occupant:get_presence();
193 if pr and (pr.attr.type ~= "unavailable" or occupant.role == nil) then
194 base_presence = st.clone(pr);
195 else -- user is leaving but didn't send a leave presence. make one for them
196 base_presence = st.presence {from = occupant.nick; type = "unavailable";};
200 -- Fire event (before full_p and anon_p are created)
202 room = self; stanza = base_presence; x = base_x;
203 occupant = occupant; nick = nick; actor = actor;
206 module:fire_event("muc-broadcast-presence", event);
208 -- Allow muc-broadcast-presence listeners to change things
211 reason = event.reason;
213 local whois = self:get_whois();
217 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
220 local full_p, full_x;
221 local function get_full_p()
222 if full_p == nil then
223 full_x = st.clone(base_x);
224 self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
225 full_p = st.clone(base_presence):add_child(full_x);
227 return full_p, full_x;
230 local anon_p, anon_x;
231 local function get_anon_p()
232 if anon_p == nil then
233 anon_x = st.clone(base_x);
234 self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
235 anon_p = st.clone(base_presence):add_child(anon_x);
237 return anon_p, anon_x;
240 local self_p, self_x;
241 if can_see_real_jids(whois, occupant) then
242 self_p, self_x = get_full_p();
244 -- Can always see your own full jids
245 -- But not allowed to see actor's
246 self_x = st.clone(base_x);
247 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
248 self_p = st.clone(base_presence):add_child(self_x);
252 for nick, n_occupant in self:each_occupant() do
253 if nick ~= occupant.nick then
255 if can_see_real_jids(whois, n_occupant) then
257 elseif occupant.bare_jid == n_occupant.bare_jid then
262 self:route_to_occupant(n_occupant, pr);
266 -- Presences for occupant itself
267 self_x:tag("status", {code = "110";}):up();
268 if occupant.role == nil then
269 -- They get an unavailable
270 self:route_to_occupant(occupant, self_p);
272 -- use their own presences as templates
273 for full_jid, pr in occupant:each_session() do
275 pr.attr.to = full_jid;
276 pr:add_child(self_x);
277 self:route_stanza(pr);
282 function room_mt:send_occupant_list(to, filter)
283 local to_bare = jid_bare(to);
284 local is_anonymous = false;
285 local whois = self:get_whois();
286 if whois ~= "anyone" then
287 local affiliation = self:get_affiliation(to);
288 if affiliation ~= "admin" and affiliation ~= "owner" then
289 local occupant = self:get_occupant_by_real_jid(to);
290 if not (occupant and can_see_real_jids(whois, occupant)) then
295 for occupant_jid, occupant in self:each_occupant() do
296 if filter == nil or filter(occupant_jid, occupant) then
297 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
298 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
299 local pres = st.clone(occupant:get_presence());
302 self:route_stanza(pres);
307 function room_mt:get_disco_info(stanza)
308 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
309 local form = dataform.new {
310 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
312 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
313 reply:add_child(form:form(nil, "result"));
316 module:hook("muc-disco#info", function(event)
317 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
319 module:hook("muc-disco#info", function(event)
320 local count = iterators.count(event.room:each_occupant());
321 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
324 function room_mt:get_disco_items(stanza)
325 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
326 for room_jid in self:each_occupant() do
327 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
332 function room_mt:handle_kickable(origin, stanza)
333 local real_jid = stanza.attr.from;
334 local occupant = self:get_occupant_by_real_jid(real_jid);
335 if occupant == nil then return nil; end
336 local type, condition, text = stanza:get_error();
337 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
339 error_message = error_message..": "..text;
341 occupant:set_session(real_jid, st.presence({type="unavailable"})
342 :tag('status'):text(error_message));
343 self:save_occupant(occupant);
344 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
345 :tag("status", {code = "307"})
346 self:publicise_occupant_status(occupant, x);
347 if occupant.jid == real_jid then -- Was last session
348 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
353 -- Give the room creator owner affiliation
354 module:hook("muc-room-pre-create", function(event)
355 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
358 -- check if user is banned
359 module:hook("muc-occupant-pre-join", function(event)
360 local room, stanza = event.room, event.stanza;
361 local affiliation = room:get_affiliation(stanza.attr.from);
362 if affiliation == "outcast" then
363 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
364 reply.tags[1].attr.code = "403";
365 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
370 function room_mt:handle_presence_to_occupant(origin, stanza)
371 local type = stanza.attr.type;
372 if type == "error" then -- error, kick em out!
373 return self:handle_kickable(origin, stanza)
374 elseif type == nil or type == "unavailable" then
375 local real_jid = stanza.attr.from;
376 local bare_jid = jid_bare(real_jid);
377 local orig_occupant, dest_occupant;
378 local is_new_room = next(self._affiliations) == nil;
380 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
381 if module:fire_event("muc-room-pre-create", {
385 }) then return true; end
387 orig_occupant = self:get_occupant_by_real_jid(real_jid);
388 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
390 local is_first_dest_session;
391 if type == "unavailable" then
392 -- dest_occupant = nil
393 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
394 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
395 dest_occupant = orig_occupant;
397 local dest_jid = stanza.attr.to;
398 dest_occupant = self:get_occupant_by_nick(dest_jid);
399 if dest_occupant == nil then
400 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
401 is_first_dest_session = true;
402 dest_occupant = self:new_occupant(bare_jid, dest_jid);
404 is_first_dest_session = false;
407 local is_last_orig_session;
408 if orig_occupant ~= nil then
409 -- Is there are least 2 sessions?
410 local iter, ob, last = orig_occupant:each_session();
411 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
414 local event, event_name = {
418 is_first_session = is_first_dest_session;
419 is_last_session = is_last_orig_session;
421 if orig_occupant == nil then
422 event_name = "muc-occupant-pre-join";
423 event.is_new_room = is_new_room;
424 event.occupant = dest_occupant;
425 elseif dest_occupant == nil then
426 event_name = "muc-occupant-pre-leave";
427 event.occupant = orig_occupant;
429 event_name = "muc-occupant-pre-change";
430 event.orig_occupant = orig_occupant;
431 event.dest_occupant = dest_occupant;
433 if module:fire_event(event_name, event) then return true; end
435 -- Check for nick conflicts
436 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
437 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
438 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
439 reply.tags[1].attr.code = "409";
440 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
444 -- Send presence stanza about original occupant
445 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
446 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
448 if dest_occupant == nil then -- Session is leaving
449 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
450 if is_last_orig_session then
451 orig_occupant.role = nil;
453 orig_occupant:set_session(real_jid, stanza);
455 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
456 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
457 orig_occupant:set_session(real_jid, generated_unavail);
458 dest_nick = select(3, jid_split(dest_occupant.nick));
459 if not is_first_dest_session then -- User is swapping into another pre-existing session
460 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
461 -- Show the other session leaving
462 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
463 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
464 add_item(x, self:get_affiliation(bare_jid), "none");
465 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
467 self:route_stanza(pr);
469 if is_first_dest_session and is_last_orig_session then -- Normal nick change
470 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
471 orig_x:tag("status", {code = "303";}):up();
472 else -- The session itself always needs to see a nick change
473 -- don't want to get our old nick's available presence,
474 -- so remove our session from there, and manually generate an unavailable
475 orig_occupant:remove_session(real_jid);
476 log("debug", "generating nick change for %s", real_jid);
477 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
478 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
479 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
480 x:tag("status", {code = "303";}):up();
481 x:tag("status", {code = "110";}):up();
482 self:route_stanza(generated_unavail:add_child(x));
483 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
486 self:save_occupant(orig_occupant);
487 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
489 if is_last_orig_session then
490 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
494 if dest_occupant ~= nil then
495 dest_occupant:set_session(real_jid, stanza);
496 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
498 dest_x:tag("status", {code = "201"}):up();
500 if orig_occupant == nil and self:get_whois() == "anyone" then
501 dest_x:tag("status", {code = "100"}):up();
503 self:save_occupant(dest_occupant);
505 if orig_occupant == nil then
506 -- Send occupant list to newly joined user
507 self:send_occupant_list(real_jid, function(nick, occupant)
508 -- Don't include self
509 return occupant:get_presence(real_jid) == nil;
512 self:publicise_occupant_status(dest_occupant, dest_x);
514 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
515 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
516 -- Show the original nick joining again
517 local pr = st.clone(orig_occupant:get_presence());
518 pr.attr.to = real_jid;
519 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
520 self:build_item_list(orig_occupant, x, false);
521 -- TODO: new status code to inform client this was the multi-session it left?
523 self:route_stanza(pr);
526 if orig_occupant == nil then
527 if is_first_dest_session then
528 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
530 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
533 elseif type ~= 'result' then -- bad type
534 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
535 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
541 function room_mt:handle_iq_to_occupant(origin, stanza)
542 local from, to = stanza.attr.from, stanza.attr.to;
543 local type = stanza.attr.type;
544 local id = stanza.attr.id;
545 local occupant = self:get_occupant_by_nick(to);
546 if (type == "error" or type == "result") then
547 do -- deconstruct_stanza_id
548 if not occupant then return nil; end
549 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
550 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
551 local from_occupant_jid = self:get_occupant_jid(from_jid);
552 if from_occupant_jid == nil then return nil; end
554 for to_jid in occupant:each_session() do
555 if md5(to_jid) == to_jid_hash then
556 session_jid = to_jid;
560 if session_jid == nil then return nil; end
561 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, id;
563 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
564 self:route_stanza(stanza);
565 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
567 else -- Type is "get" or "set"
568 local current_nick = self:get_occupant_jid(from);
569 if not current_nick then
570 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
573 if not occupant then -- recipient not in room
574 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
577 do -- construct_stanza_id
578 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
580 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
581 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
582 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
583 stanza.attr.to = jid_bare(stanza.attr.to);
585 self:route_stanza(stanza);
586 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
591 function room_mt:handle_message_to_occupant(origin, stanza)
592 local from, to = stanza.attr.from, stanza.attr.to;
593 local current_nick = self:get_occupant_jid(from);
594 local type = stanza.attr.type;
595 if not current_nick then -- not in room
596 if type ~= "error" then
597 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
601 if type == "groupchat" then -- groupchat messages not allowed in PM
602 origin.send(st.error_reply(stanza, "modify", "bad-request"));
604 elseif type == "error" and is_kickable_error(stanza) then
605 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
606 return self:handle_kickable(origin, stanza); -- send unavailable
609 local o_data = self:get_occupant_by_nick(to);
611 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
614 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
615 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
616 stanza.attr.from = current_nick;
617 self:route_to_occupant(o_data, stanza)
618 -- TODO: Remove x tag?
619 stanza.attr.from = from;
623 function room_mt:send_form(origin, stanza)
624 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
625 :add_child(self:get_form_layout(stanza.attr.from):form())
629 function room_mt:get_form_layout(actor)
630 local form = dataform.new({
631 title = "Configuration for "..self.jid,
632 instructions = "Complete and submit this form to configure the room.",
636 value = 'http://jabber.org/protocol/muc#roomconfig'
639 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
642 function room_mt:process_form(origin, stanza)
643 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
644 if form.attr.type == "cancel" then
645 origin.send(st.reply(stanza));
646 elseif form.attr.type == "submit" then
647 local fields, errors, present;
648 if form.tags[1] == nil then -- Instant room
649 fields, present = {}, {};
651 fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
652 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
653 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
658 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
659 function event.update_option(name, field, allowed)
660 local new = fields[field];
661 if new == nil then return; end
662 if allowed and not allowed[new] then return; end
663 if new == self["get_"..name](self) then return; end
664 event.status_codes["104"] = true;
665 self["set_"..name](self, new);
668 module:fire_event("muc-config-submitted", event);
669 for submitted_field in pairs(present) do
670 event.field, event.value = submitted_field, fields[submitted_field];
671 module:fire_event("muc-config-submitted/"..submitted_field, event);
673 event.field, event.value = nil, nil;
675 if self.save then self:save(true); end
676 origin.send(st.reply(stanza));
678 if next(event.status_codes) then
679 local msg = st.message({type='groupchat', from=self.jid})
680 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
681 for code in pairs(event.status_codes) do
682 msg:tag("status", {code = code;}):up();
685 self:broadcast_message(msg);
688 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
693 -- Removes everyone from the room
694 function room_mt:clear(x)
695 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
696 local occupants_updated = {};
697 for nick, occupant in self:each_occupant() do
699 self:save_occupant(occupant);
700 occupants_updated[occupant] = true;
702 for occupant in pairs(occupants_updated) do
703 self:publicise_occupant_status(occupant, x);
704 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
708 function room_mt:destroy(newjid, reason, password)
709 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
710 :tag("item", { affiliation='none', role='none' }):up()
711 :tag("destroy", {jid=newjid});
712 if reason then x:tag("reason"):text(reason):up(); end
713 if password then x:tag("password"):text(password):up(); end
716 module:fire_event("muc-room-destroyed", { room = self });
719 function room_mt:handle_disco_info_get_query(origin, stanza)
720 origin.send(self:get_disco_info(stanza));
724 function room_mt:handle_disco_items_get_query(origin, stanza)
725 origin.send(self:get_disco_items(stanza));
729 function room_mt:handle_admin_query_set_command(origin, stanza)
730 local item = stanza.tags[1].tags[1];
732 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
734 if item.attr.jid then -- Validate provided JID
735 item.attr.jid = jid_prep(item.attr.jid);
736 if not item.attr.jid then
737 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
741 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
742 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
743 if occupant then item.attr.jid = occupant.jid; end
744 elseif not item.attr.nick and item.attr.jid then
745 local nick = self:get_occupant_jid(item.attr.jid);
746 if nick then item.attr.nick = select(3, jid_split(nick)); end
748 local actor = stanza.attr.from;
749 local reason = item:get_child_text("reason");
750 local success, errtype, err
751 if item.attr.affiliation and item.attr.jid and not item.attr.role then
752 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
753 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
754 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
756 success, errtype, err = nil, "cancel", "bad-request";
759 origin.send(st.error_reply(stanza, errtype, err));
761 origin.send(st.reply(stanza));
766 function room_mt:handle_admin_query_get_command(origin, stanza)
767 local actor = stanza.attr.from;
768 local affiliation = self:get_affiliation(actor);
769 local item = stanza.tags[1].tags[1];
770 local _aff = item.attr.affiliation;
771 local _aff_rank = valid_affiliations[_aff or "none"];
772 local _rol = item.attr.role;
773 if _aff and _aff_rank and not _rol then
774 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
775 -- e.g. an admin can't ask for a list of owners
776 local affiliation_rank = valid_affiliations[affiliation or "none"];
777 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
778 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
779 for jid in self:each_affiliation(_aff or "none") do
780 reply:tag("item", {affiliation = _aff, jid = jid}):up();
782 origin.send(reply:up());
785 origin.send(st.error_reply(stanza, "auth", "forbidden"));
788 elseif _rol and valid_roles[_rol or "none"] and not _aff then
789 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
790 if valid_roles[role or "none"] >= valid_roles.moderator then
791 if _rol == "none" then _rol = nil; end
792 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
793 -- TODO: whois check here? (though fully anonymous rooms are not supported)
794 for occupant_jid, occupant in self:each_occupant() do
795 if occupant.role == _rol then
796 local nick = select(3,jid_split(occupant_jid));
797 self:build_item_list(occupant, reply, false, nick);
800 origin.send(reply:up());
803 origin.send(st.error_reply(stanza, "auth", "forbidden"));
807 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
812 function room_mt:handle_owner_query_get_to_room(origin, stanza)
813 if self:get_affiliation(stanza.attr.from) ~= "owner" then
814 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
818 self:send_form(origin, stanza);
821 function room_mt:handle_owner_query_set_to_room(origin, stanza)
822 if self:get_affiliation(stanza.attr.from) ~= "owner" then
823 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
827 local child = stanza.tags[1].tags[1];
829 origin.send(st.error_reply(stanza, "modify", "bad-request"));
831 elseif child.name == "destroy" then
832 local newjid = child.attr.jid;
833 local reason = child:get_child_text("reason");
834 local password = child:get_child_text("password");
835 self:destroy(newjid, reason, password);
836 origin.send(st.reply(stanza));
838 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
839 return self:process_form(origin, stanza);
841 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
846 function room_mt:handle_groupchat_to_room(origin, stanza)
847 local from = stanza.attr.from;
848 local occupant = self:get_occupant_by_real_jid(from);
849 if module:fire_event("muc-occupant-groupchat", {
850 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
851 }) then return true; end
852 stanza.attr.from = occupant.nick;
853 self:broadcast_message(stanza);
854 stanza.attr.from = from;
859 module:hook("muc-occupant-groupchat", function(event)
860 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
861 if role_rank <= valid_roles.none then
862 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
864 elseif role_rank <= valid_roles.visitor then
865 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
870 -- hack - some buggy clients send presence updates to the room rather than their nick
871 function room_mt:handle_presence_to_room(origin, stanza)
872 local current_nick = self:get_occupant_jid(stanza.attr.from);
875 local to = stanza.attr.to;
876 stanza.attr.to = current_nick;
877 handled = self:handle_presence_to_occupant(origin, stanza);
883 -- Need visitor role or higher to invite
884 module:hook("muc-pre-invite", function(event)
885 local room, stanza = event.room, event.stanza;
886 local _from, _to = stanza.attr.from, stanza.attr.to;
887 local inviter = room:get_occupant_by_real_jid(_from);
888 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
889 if valid_roles[role or "none"] <= valid_roles.visitor then
890 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
895 function room_mt:handle_mediated_invite(origin, stanza)
896 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
897 local invitee = jid_prep(payload.attr.to);
899 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
901 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
904 local invite = muc_util.filter_muc_x(st.clone(stanza));
905 invite.attr.from = self.jid;
906 invite.attr.to = invitee;
907 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
908 :tag('invite', {from = stanza.attr.from;})
909 :tag('reason'):text(payload:get_child_text("reason")):up()
912 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
913 self:route_stanza(invite);
918 -- COMPAT: Some older clients expect this
919 module:hook("muc-invite", function(event)
920 local room, stanza = event.room, event.stanza;
921 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
922 local reason = invite:get_child_text("reason");
923 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
928 -- Add a plain message for clients which don't support invites
929 module:hook("muc-invite", function(event)
930 local room, stanza = event.room, event.stanza;
931 if not stanza:get_child("body") then
932 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
933 local reason = invite:get_child_text("reason") or "";
935 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
940 function room_mt:handle_mediated_decline(origin, stanza)
941 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
942 local declinee = jid_prep(payload.attr.to);
944 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
946 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
949 local decline = muc_util.filter_muc_x(st.clone(stanza));
950 decline.attr.from = self.jid;
951 decline.attr.to = declinee;
952 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
953 :tag("decline", {from = stanza.attr.from})
954 :tag("reason"):text(payload:get_child_text("reason")):up()
957 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
958 local declinee = decline.attr.to; -- re-fetch, in case event modified it
960 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
961 occupant = self:get_occupant_by_nick(declinee);
964 self:route_to_occupant(occupant, decline);
966 self:route_stanza(decline);
972 -- Add a plain message for clients which don't support declines
973 module:hook("muc-decline", function(event)
974 local room, stanza = event.room, event.stanza;
975 if not stanza:get_child("body") then
976 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
977 local reason = decline:get_child_text("reason") or "";
979 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
984 function room_mt:handle_message_to_room(origin, stanza)
985 local type = stanza.attr.type;
986 if type == "groupchat" then
987 return self:handle_groupchat_to_room(origin, stanza)
988 elseif type == "error" and is_kickable_error(stanza) then
989 return self:handle_kickable(origin, stanza)
990 elseif type == nil then
991 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
993 local payload = x.tags[1];
994 if payload == nil then
996 elseif payload.name == "invite" and payload.attr.to then
997 return self:handle_mediated_invite(origin, stanza)
998 elseif payload.name == "decline" and payload.attr.to then
999 return self:handle_mediated_decline(origin, stanza)
1001 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1007 function room_mt:route_stanza(stanza)
1008 module:send(stanza);
1011 function room_mt:get_affiliation(jid)
1012 local node, host, resource = jid_split(jid);
1013 local bare = node and node.."@"..host or host;
1014 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1015 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1019 -- Iterates over jid, affiliation pairs
1020 function room_mt:each_affiliation(with_affiliation)
1021 if not with_affiliation then
1022 return pairs(self._affiliations);
1024 return function(_affiliations, jid)
1026 repeat -- Iterate until we get a match
1027 jid, affiliation = next(_affiliations, jid);
1028 until jid == nil or affiliation == with_affiliation
1029 return jid, affiliation;
1030 end, self._affiliations, nil
1034 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1035 if not actor then return nil, "modify", "not-acceptable"; end;
1037 local node, host, resource = jid_split(jid);
1038 if not host then return nil, "modify", "not-acceptable"; end
1039 jid = jid_join(node, host); -- Bare
1040 local is_host_only = node == nil;
1042 if valid_affiliations[affiliation or "none"] == nil then
1043 return nil, "modify", "not-acceptable";
1045 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1047 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1048 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1050 if actor == true then
1051 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1053 local actor_affiliation = self:get_affiliation(actor);
1054 if actor_affiliation == "owner" then
1055 if jid_bare(actor) == jid then -- self change
1056 -- need at least one owner
1057 local is_last = true;
1058 for j in self:each_affiliation("owner") do
1059 if j ~= jid then is_last = false; break; end
1062 return nil, "cancel", "conflict";
1065 -- owners can do anything else
1066 elseif affiliation == "owner" or affiliation == "admin"
1067 or actor_affiliation ~= "admin"
1068 or target_affiliation == "owner" or target_affiliation == "admin" then
1069 -- Can't demote owners or other admins
1070 return nil, "cancel", "not-allowed";
1074 -- Set in 'database'
1075 self._affiliations[jid] = affiliation;
1078 local role = self:get_default_role(affiliation);
1079 local role_rank = valid_roles[role or "none"];
1080 local occupants_updated = {}; -- Filled with old roles
1081 for nick, occupant in self:each_occupant() do
1082 if occupant.bare_jid == jid or (
1083 -- Outcast can be by host.
1084 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1086 -- need to publcize in all cases; as affiliation in <item/> has changed.
1087 occupants_updated[occupant] = occupant.role;
1088 if occupant.role ~= role and (
1090 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1092 occupant.role = role;
1093 self:save_occupant(occupant);
1098 -- Tell the room of the new occupant affiliations+roles
1099 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1100 if not role then -- getting kicked
1101 if affiliation == "outcast" then
1102 x:tag("status", {code="301"}):up(); -- banned
1104 x:tag("status", {code="321"}):up(); -- affiliation change
1107 local is_semi_anonymous = self:get_whois() == "moderators";
1108 for occupant, old_role in pairs(occupants_updated) do
1109 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1110 if occupant.role == nil then
1111 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1112 elseif is_semi_anonymous and
1113 (old_role == "moderator" and occupant.role ~= "moderator") or
1114 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1115 -- Send everyone else's presences (as jid visibility has changed)
1116 for real_jid in occupant:each_session() do
1117 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1118 return occupant.bare_jid ~= jid;
1124 if self.save then self:save(); end
1126 module:fire_event("muc-set-affiliation", {
1130 affiliation = affiliation or "none";
1132 previous_affiliation = target_affiliation;
1133 in_room = next(occupants_updated) ~= nil;
1139 function room_mt:get_role(nick)
1140 local occupant = self:get_occupant_by_nick(nick);
1141 return occupant and occupant.role or nil;
1144 function room_mt:set_role(actor, occupant_jid, role, reason)
1145 if not actor then return nil, "modify", "not-acceptable"; end
1147 local occupant = self:get_occupant_by_nick(occupant_jid);
1148 if not occupant then return nil, "modify", "not-acceptable"; end
1150 if valid_roles[role or "none"] == nil then
1151 return nil, "modify", "not-acceptable";
1153 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1155 if actor == true then
1156 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1158 -- Can't do anything to other owners or admins
1159 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1160 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1161 return nil, "cancel", "not-allowed";
1164 -- If you are trying to give or take moderator role you need to be an owner or admin
1165 if occupant.role == "moderator" or role == "moderator" then
1166 local actor_affiliation = self:get_affiliation(actor);
1167 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1168 return nil, "cancel", "not-allowed";
1172 -- Need to be in the room and a moderator
1173 local actor_occupant = self:get_occupant_by_real_jid(actor);
1174 if not actor_occupant or actor_occupant.role ~= "moderator" then
1175 return nil, "cancel", "not-allowed";
1179 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1181 x:tag("status", {code = "307"}):up();
1183 occupant.role = role;
1184 self:save_occupant(occupant);
1185 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1187 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1192 local whois = module:require "muc/whois";
1193 room_mt.get_whois = whois.get;
1194 room_mt.set_whois = whois.set;
1196 local _M = {}; -- module "muc"
1198 function _M.new_room(jid, config)
1199 return setmetatable({
1209 _M.room_mt = room_mt;