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 st = require "util.stanza";
21 local log = require "util.logger".init("mod_muc");
22 local base64 = require "util.encodings".base64;
23 local md5 = require "util.hashes".md5;
25 local occupant_lib = module:require "muc/occupant"
26 local muc_util = module:require "muc/util";
27 local is_kickable_error = muc_util.is_kickable_error;
28 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
31 room_mt.__index = room_mt;
33 function room_mt:__tostring()
34 return "MUC room ("..self.jid..")";
37 function room_mt:get_occupant_jid(real_jid)
38 return self._jid_nick[real_jid]
41 function room_mt:get_default_role(affiliation)
42 local role = module:fire_event("muc-get-default-role", {
44 affiliation = affiliation;
45 affiliation_rank = valid_affiliations[affiliation or "none"];
47 return role, valid_roles[role or "none"];
49 module:hook("muc-get-default-role", function(event)
50 if event.affiliation_rank >= valid_affiliations.admin then
52 elseif event.affiliation_rank >= valid_affiliations.none then
57 --- Occupant functions
58 function room_mt:new_occupant(bare_real_jid, nick)
59 local occupant = occupant_lib.new(bare_real_jid, nick);
60 local affiliation = self:get_affiliation(bare_real_jid);
61 occupant.role = self:get_default_role(affiliation);
65 function room_mt:get_occupant_by_nick(nick)
66 local occupant = self._occupants[nick];
67 if occupant == nil then return nil end
68 return occupant_lib.copy(occupant);
72 local function next_copied_occupant(occupants, occupant_jid)
73 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
74 if next_occupant_jid == nil then return nil end
75 return next_occupant_jid, occupant_lib.copy(raw_occupant);
77 function room_mt:each_occupant(read_only)
78 return next_copied_occupant, self._occupants, nil;
82 function room_mt:has_occupant()
83 return next(self._occupants, nil) ~= nil
86 function room_mt:get_occupant_by_real_jid(real_jid)
87 local occupant_jid = self:get_occupant_jid(real_jid);
88 if occupant_jid == nil then return nil end
89 return self:get_occupant_by_nick(occupant_jid);
92 function room_mt:save_occupant(occupant)
93 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
94 local id = occupant.nick
96 -- Need to maintain _jid_nick secondary index
97 local old_occupant = self._occupants[id];
99 for real_jid in pairs(old_occupant.sessions) do
100 self._jid_nick[real_jid] = nil;
104 local has_live_session = false
105 if occupant.role ~= nil then
106 for real_jid, presence in occupant:each_session() do
107 if presence.attr.type == nil then
108 has_live_session = true
109 self._jid_nick[real_jid] = occupant.nick;
112 if not has_live_session then
113 -- Has no live sessions left; they have left the room.
117 if not has_live_session then
120 self._occupants[id] = occupant
123 function room_mt:route_to_occupant(occupant, stanza)
124 local to = stanza.attr.to;
125 for jid, pr in occupant:each_session() do
126 stanza.attr.to = jid;
127 self:route_stanza(stanza);
132 -- actor is the attribute table
133 local function add_item(x, affiliation, role, jid, nick, actor, reason)
134 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
136 x:tag("actor", actor):up()
139 x:tag("reason"):text(reason):up()
145 -- actor is (real) jid
146 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
147 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
148 local role = occupant.role or "none";
151 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
154 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
157 actor_attr.jid = actor;
159 for real_jid, session in occupant:each_session() do
160 add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
166 function room_mt:broadcast_message(stanza)
167 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
170 self:broadcast(stanza);
174 -- Broadcast a stanza to all occupants in the room.
175 -- optionally checks conditional called with (nick, occupant)
176 function room_mt:broadcast(stanza, cond_func)
177 for nick, occupant in self:each_occupant() do
178 if cond_func == nil or cond_func(nick, occupant) then
179 self:route_to_occupant(occupant, stanza)
184 local function can_see_real_jids(whois, occupant)
185 if whois == "anyone" then
187 elseif whois == "moderators" then
188 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
192 -- Broadcasts an occupant's presence to the whole room
193 -- Takes the x element that goes into the stanzas
194 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
195 -- Build real jid and (optionally) occupant jid template presences
197 if occupant.role ~= nil then
198 -- Try to use main jid's presence
199 local pr = occupant:get_presence();
201 base_presence = st.clone(pr);
204 base_presence = base_presence or st.presence {from = occupant.nick; type = "unavailable";};
206 -- Fire event (before full_p and anon_p are created)
207 module:fire_event("muc-broadcast-presence", {
208 room = self; stanza = base_presence; x = base_x;
209 occupant = occupant; nick = nick; actor = actor;
213 local function get_presence(is_anonymous)
214 local x = st.clone(base_x);
215 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
216 return st.clone(base_presence):add_child(x), x;
219 local full_p, full_x = get_presence(false);
221 -- Create anon_p lazily
222 local anon_p, anon_x;
223 local function get_anon_p()
224 if anon_p == nil then
225 anon_p, anon_x = get_presence(true);
227 return anon_p, anon_x;
230 local whois = self:get_whois();
233 for nick, n_occupant in self:each_occupant() do
234 if nick ~= occupant.nick then
236 if can_see_real_jids(whois, n_occupant) or occupant.bare_jid == n_occupant.bare_jid then
241 self:route_to_occupant(n_occupant, pr);
245 -- Presences for occupant itself
246 full_x:tag("status", {code = "110";}):up();
247 if occupant.role == nil then
248 -- They get an unavailable
249 self:route_to_occupant(occupant, full_p);
251 -- use their own presences as templates
252 for full_jid, pr in occupant:each_session() do
254 pr.attr.to = full_jid;
255 -- You can always see your own full jids
256 pr:add_child(full_x);
257 self:route_stanza(pr);
262 function room_mt:send_occupant_list(to, filter)
263 local to_bare = jid_bare(to);
264 local is_anonymous = false;
265 local whois = self:get_whois();
266 if whois ~= "anyone" then
267 local affiliation = self:get_affiliation(to);
268 if affiliation ~= "admin" and affiliation ~= "owner" then
269 local occupant = self:get_occupant_by_real_jid(to);
270 if not (occupant and can_see_real_jids(whois, occupant)) then
275 for occupant_jid, occupant in self:each_occupant() do
276 if filter == nil or filter(occupant_jid, occupant) then
277 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
278 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
279 local pres = st.clone(occupant:get_presence());
282 self:route_stanza(pres);
287 function room_mt:get_disco_info(stanza)
288 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
289 local form = dataform.new {
290 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
292 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
293 reply:add_child(form:form(nil, "result"));
296 module:hook("muc-disco#info", function(event)
297 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
299 module:hook("muc-disco#info", function(event)
300 local count = iterators.count(event.room:each_occupant());
301 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
304 function room_mt:get_disco_items(stanza)
305 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
306 for room_jid in self:each_occupant() do
307 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
312 function room_mt:handle_kickable(origin, stanza)
313 local real_jid = stanza.attr.from;
314 local occupant = self:get_occupant_by_real_jid(real_jid);
315 if occupant == nil then return nil; end
316 local type, condition, text = stanza:get_error();
317 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
319 error_message = error_message..": "..text;
321 occupant:set_session(real_jid, st.presence({type="unavailable"})
322 :tag('status'):text(error_message));
323 self:save_occupant(occupant);
324 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
325 :tag("status", {code = "307"})
326 self:publicise_occupant_status(occupant, x);
330 -- Give the room creator owner affiliation
331 module:hook("muc-room-pre-create", function(event)
332 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
335 -- check if user is banned
336 module:hook("muc-occupant-pre-join", function(event)
337 local room, stanza = event.room, event.stanza;
338 local affiliation = room:get_affiliation(stanza.attr.from);
339 if affiliation == "outcast" then
340 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
341 reply.tags[1].attr.code = "403";
342 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
347 function room_mt:handle_presence_to_occupant(origin, stanza)
348 local type = stanza.attr.type;
349 if type == "error" then -- error, kick em out!
350 return self:handle_kickable(origin, stanza)
351 elseif type == nil or type == "unavailable" then
352 local real_jid = stanza.attr.from;
353 local bare_jid = jid_bare(real_jid);
354 local orig_occupant, dest_occupant;
355 local is_new_room = next(self._affiliations) == nil;
357 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
358 if module:fire_event("muc-room-pre-create", {
362 }) then return true; end
364 orig_occupant = self:get_occupant_by_real_jid(real_jid);
365 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
367 local is_first_dest_session;
368 if type == "unavailable" then
369 -- dest_occupant = nil
370 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
371 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
372 dest_occupant = orig_occupant;
374 local dest_jid = stanza.attr.to;
375 dest_occupant = self:get_occupant_by_nick(dest_jid);
376 if dest_occupant == nil then
377 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
378 is_first_dest_session = true;
379 dest_occupant = self:new_occupant(bare_jid, dest_jid);
381 is_first_dest_session = false;
384 local is_last_orig_session;
385 if orig_occupant ~= nil then
386 -- Is there are least 2 sessions?
387 local iter, ob, last = orig_occupant:each_session();
388 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
391 local event, event_name = {
395 is_first_session = is_first_dest_session;
396 is_last_session = is_last_orig_session;
398 if orig_occupant == nil then
399 event_name = "muc-occupant-pre-join";
400 event.is_new_room = is_new_room;
401 elseif dest_occupant == nil then
402 event_name = "muc-occupant-pre-leave";
404 event_name = "muc-occupant-pre-change";
406 if module:fire_event(event_name, event) then return true; end
408 -- Check for nick conflicts
409 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
410 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
411 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
412 reply.tags[1].attr.code = "409";
413 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
417 -- Send presence stanza about original occupant
418 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
419 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
421 if dest_occupant == nil then -- Session is leaving
422 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
423 if is_last_orig_session then
424 orig_occupant.role = nil;
426 orig_occupant:set_session(real_jid, stanza);
428 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
429 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
430 orig_occupant:set_session(real_jid, generated_unavail);
431 dest_nick = select(3, jid_split(dest_occupant.nick));
432 if not is_first_dest_session then -- User is swapping into another pre-existing session
433 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
434 -- Show the other session leaving
435 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
436 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
437 add_item(x, self:get_affiliation(bare_jid), "none");
438 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
440 self:route_stanza(pr);
442 if is_first_dest_session and is_last_orig_session then -- Normal nick change
443 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
444 orig_x:tag("status", {code = "303";}):up();
445 else -- The session itself always needs to see a nick change
446 -- don't want to get our old nick's available presence,
447 -- so remove our session from there, and manually generate an unavailable
448 orig_occupant:remove_session(real_jid);
449 log("debug", "generating nick change for %s", real_jid);
450 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
451 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
452 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
453 x:tag("status", {code = "303";}):up();
454 x:tag("status", {code = "110";}):up();
455 self:route_stanza(generated_unavail:add_child(x));
456 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
459 self:save_occupant(orig_occupant);
460 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
462 if is_last_orig_session then
463 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick;});
467 if dest_occupant ~= nil then
468 dest_occupant:set_session(real_jid, stanza);
469 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
471 dest_x:tag("status", {code = "201"}):up();
473 if orig_occupant == nil and self:get_whois() == "anyone" then
474 dest_x:tag("status", {code = "100"}):up();
476 self:save_occupant(dest_occupant);
478 if orig_occupant == nil then
479 -- Send occupant list to newly joined user
480 self:send_occupant_list(real_jid, function(nick, occupant)
481 -- Don't include self
482 return occupant:get_presence(real_jid) == nil;
485 self:publicise_occupant_status(dest_occupant, dest_x);
487 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
488 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
489 -- Show the original nick joining again
490 local pr = st.clone(orig_occupant:get_presence());
491 pr.attr.to = real_jid;
492 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
493 self:build_item_list(orig_occupant, x, false);
494 -- TODO: new status code to inform client this was the multi-session it left?
496 self:route_stanza(pr);
499 if orig_occupant == nil then
500 if is_first_dest_session then
501 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; stanza = stanza;});
503 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; stanza = stanza; jid = real_jid;});
506 elseif type ~= 'result' then -- bad type
507 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
508 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
514 function room_mt:handle_iq_to_occupant(origin, stanza)
515 local from, to = stanza.attr.from, stanza.attr.to;
516 local type = stanza.attr.type;
517 local id = stanza.attr.id;
518 local occupant = self:get_occupant_by_nick(to);
519 if (type == "error" or type == "result") then
520 do -- deconstruct_stanza_id
521 if not occupant then return nil; end
522 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
523 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
524 local from_occupant_jid = self:get_occupant_jid(from_jid);
525 if from_occupant_jid == nil then return nil; end
527 for to_jid in occupant:each_session() do
528 if md5(to_jid) == to_jid_hash then
529 session_jid = to_jid;
533 if session_jid == nil then return nil; end
534 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_jid, session_jid, id;
536 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
537 self:route_stanza(stanza);
538 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
540 else -- Type is "get" or "set"
541 local current_nick = self:get_occupant_jid(from);
542 if not current_nick then
543 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
546 if not occupant then -- recipient not in room
547 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
550 do -- construct_stanza_id
551 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
553 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
554 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
555 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
556 stanza.attr.to = jid_bare(stanza.attr.to);
558 self:route_stanza(stanza);
559 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
564 function room_mt:handle_message_to_occupant(origin, stanza)
565 local from, to = stanza.attr.from, stanza.attr.to;
566 local current_nick = self:get_occupant_jid(from);
567 local type = stanza.attr.type;
568 if not current_nick then -- not in room
569 if type ~= "error" then
570 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
574 if type == "groupchat" then -- groupchat messages not allowed in PM
575 origin.send(st.error_reply(stanza, "modify", "bad-request"));
577 elseif type == "error" and is_kickable_error(stanza) then
578 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
579 return self:handle_kickable(origin, stanza); -- send unavailable
582 local o_data = self:get_occupant_by_nick(to);
584 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
587 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
588 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
589 stanza.attr.from = current_nick;
590 self:route_to_occupant(o_data, stanza)
591 -- TODO: Remove x tag?
592 stanza.attr.from = from;
596 function room_mt:send_form(origin, stanza)
597 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
598 :add_child(self:get_form_layout(stanza.attr.from):form())
602 function room_mt:get_form_layout(actor)
603 local form = dataform.new({
604 title = "Configuration for "..self.jid,
605 instructions = "Complete and submit this form to configure the room.",
609 value = 'http://jabber.org/protocol/muc#roomconfig'
612 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
615 function room_mt:process_form(origin, stanza)
616 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
617 if form.attr.type == "cancel" then
618 origin.send(st.reply(stanza));
619 elseif form.attr.type == "submit" then
621 if form.tags[1] == nil then -- Instant room
624 fields = self:get_form_layout(stanza.attr.from):data(form);
625 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
626 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
631 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
632 function event.update_option(name, field, allowed)
633 local new = fields[field];
634 if new == nil then return; end
635 if allowed and not allowed[new] then return; end
636 if new == self["get_"..name](self) then return; end
637 event.status_codes["104"] = true;
638 self["set_"..name](self, new);
641 module:fire_event("muc-config-submitted", event);
643 if self.save then self:save(true); end
644 origin.send(st.reply(stanza));
646 if next(event.status_codes) then
647 local msg = st.message({type='groupchat', from=self.jid})
648 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
649 for code in pairs(event.status_codes) do
650 msg:tag("status", {code = code;}):up();
653 self:broadcast_message(msg);
656 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
661 -- Removes everyone from the room
662 function room_mt:clear(x)
663 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
664 local occupants_updated = {};
665 for nick, occupant in self:each_occupant() do
667 self:save_occupant(occupant);
668 occupants_updated[occupant] = true;
670 for occupant in pairs(occupants_updated) do
671 self:publicise_occupant_status(occupant, x);
672 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; });
676 function room_mt:destroy(newjid, reason, password)
677 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
678 :tag("item", { affiliation='none', role='none' }):up()
679 :tag("destroy", {jid=newjid});
680 if reason then x:tag("reason"):text(reason):up(); end
681 if password then x:tag("password"):text(password):up(); end
684 module:fire_event("muc-room-destroyed", { room = self });
687 function room_mt:handle_disco_info_get_query(origin, stanza)
688 origin.send(self:get_disco_info(stanza));
692 function room_mt:handle_disco_items_get_query(origin, stanza)
693 origin.send(self:get_disco_items(stanza));
697 function room_mt:handle_admin_query_set_command(origin, stanza)
698 local item = stanza.tags[1].tags[1];
699 if item.attr.jid then -- Validate provided JID
700 item.attr.jid = jid_prep(item.attr.jid);
701 if not item.attr.jid then
702 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
706 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
707 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
708 if occupant then item.attr.jid = occupant.jid; end
709 elseif not item.attr.nick and item.attr.jid then
710 local nick = self:get_occupant_jid(item.attr.jid);
711 if nick then item.attr.nick = select(3, jid_split(nick)); end
713 local actor = stanza.attr.from;
714 local reason = item:get_child_text("reason");
715 local success, errtype, err
716 if item.attr.affiliation and item.attr.jid and not item.attr.role then
717 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
718 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
719 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
721 success, errtype, err = nil, "cancel", "bad-request";
723 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
724 origin.send(st.reply(stanza));
728 function room_mt:handle_admin_query_get_command(origin, stanza)
729 local actor = stanza.attr.from;
730 local affiliation = self:get_affiliation(actor);
731 local item = stanza.tags[1].tags[1];
732 local _aff = item.attr.affiliation;
733 local _rol = item.attr.role;
734 if _aff and not _rol then
735 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
736 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
737 for jid, affiliation in pairs(self._affiliations) do
738 if affiliation == _aff then
739 reply:tag("item", {affiliation = _aff, jid = jid}):up();
745 origin.send(st.error_reply(stanza, "auth", "forbidden"));
748 elseif _rol and not _aff then
749 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
750 if valid_roles[role or "none"] >= valid_roles.moderator then
751 if _rol == "none" then _rol = nil; end
752 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
753 -- TODO: whois check here? (though fully anonymous rooms are not supported)
754 for occupant_jid, occupant in self:each_occupant() do
755 if occupant.role == _rol then
756 local nick = select(3,jid_split(occupant_jid));
757 self:build_item_list(occupant, reply, false, nick);
760 origin.send(reply:up());
763 origin.send(st.error_reply(stanza, "auth", "forbidden"));
767 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
772 function room_mt:handle_owner_query_get_to_room(origin, stanza)
773 if self:get_affiliation(stanza.attr.from) ~= "owner" then
774 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
778 self:send_form(origin, stanza);
781 function room_mt:handle_owner_query_set_to_room(origin, stanza)
782 if self:get_affiliation(stanza.attr.from) ~= "owner" then
783 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
787 local child = stanza.tags[1].tags[1];
789 origin.send(st.error_reply(stanza, "modify", "bad-request"));
791 elseif child.name == "destroy" then
792 local newjid = child.attr.jid;
793 local reason = child:get_child_text("reason");
794 local password = child:get_child_text("password");
795 self:destroy(newjid, reason, password);
796 origin.send(st.reply(stanza));
798 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
799 return self:process_form(origin, stanza);
801 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
806 function room_mt:handle_groupchat_to_room(origin, stanza)
807 -- Prosody has made the decision that messages with <subject/> are exclusively subject changes
808 -- e.g. body will be ignored; even if the subject change was not allowed
809 if stanza:get_child("subject") then
810 return module:fire_event("muc-subject-change", {room = self, origin = origin, stanza = stanza});
812 local from = stanza.attr.from;
813 local occupant = self:get_occupant_by_real_jid(from);
814 if not occupant then -- not in room
815 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
817 elseif occupant.role == "visitor" then
818 origin.send(st.error_reply(stanza, "auth", "forbidden"));
821 stanza.attr.from = occupant.nick;
822 self:broadcast_message(stanza);
823 stanza.attr.from = from;
827 -- hack - some buggy clients send presence updates to the room rather than their nick
828 function room_mt:handle_presence_to_room(origin, stanza)
829 local current_nick = self:get_occupant_jid(stanza.attr.from);
832 local to = stanza.attr.to;
833 stanza.attr.to = current_nick;
834 handled = self:handle_presence_to_occupant(origin, stanza);
840 -- Need visitor role or higher to invite
841 module:hook("muc-pre-invite", function(event)
842 local room, stanza = event.room, event.stanza;
843 local _from, _to = stanza.attr.from, stanza.attr.to;
844 local inviter = room:get_occupant_by_real_jid(_from);
845 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
846 if valid_roles[role or "none"] <= valid_roles.visitor then
847 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
852 function room_mt:handle_mediated_invite(origin, stanza)
853 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
854 local invitee = jid_prep(payload.attr.to);
856 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
858 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
861 local invite = muc_util.filter_muc_x(st.clone(stanza));
862 invite.attr.from = self.jid;
863 invite.attr.to = invitee;
864 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
865 :tag('invite', {from = stanza.attr.from;})
866 :tag('reason'):text(payload:get_child_text("reason")):up()
869 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
870 self:route_stanza(invite);
875 -- COMPAT: Some older clients expect this
876 module:hook("muc-invite", function(event)
877 local room, stanza = event.room, event.stanza;
878 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
879 local reason = invite:get_child_text("reason");
880 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
885 -- Add a plain message for clients which don't support invites
886 module:hook("muc-invite", function(event)
887 local room, stanza = event.room, event.stanza;
888 if not stanza:get_child("body") then
889 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
890 local reason = invite:get_child_text("reason") or "";
892 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
897 function room_mt:handle_mediated_decline(origin, stanza)
898 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
899 local declinee = jid_prep(payload.attr.to);
901 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
903 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
906 local decline = muc_util.filter_muc_x(st.clone(stanza));
907 decline.attr.from = self.jid;
908 decline.attr.to = declinee;
909 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
910 :tag("decline", {from = stanza.attr.from})
911 :tag("reason"):text(payload:get_child_text("reason")):up()
914 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
915 local declinee = decline.attr.to; -- re-fetch, in case event modified it
917 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
918 occupant = self:get_occupant_by_nick(declinee);
921 self:route_to_occupant(occupant, decline);
923 self:route_stanza(decline);
929 -- Add a plain message for clients which don't support declines
930 module:hook("muc-decline", function(event)
931 local room, stanza = event.room, event.stanza;
932 if not stanza:get_child("body") then
933 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
934 local reason = decline:get_child_text("reason") or "";
936 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
941 function room_mt:handle_message_to_room(origin, stanza)
942 local type = stanza.attr.type;
943 if type == "groupchat" then
944 return self:handle_groupchat_to_room(origin, stanza)
945 elseif type == "error" and is_kickable_error(stanza) then
946 return self:handle_kickable(origin, stanza)
947 elseif type == nil then
948 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
950 local payload = x.tags[1];
951 if payload == nil then
953 elseif payload.name == "invite" and payload.attr.to then
954 return self:handle_mediated_invite(origin, stanza)
955 elseif payload.name == "decline" and payload.attr.to then
956 return self:handle_mediated_decline(origin, stanza)
958 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
964 function room_mt:route_stanza(stanza)
968 function room_mt:get_affiliation(jid)
969 local node, host, resource = jid_split(jid);
970 local bare = node and node.."@"..host or host;
971 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
972 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
976 function room_mt:set_affiliation(actor, jid, affiliation, reason)
977 if not actor then return nil, "modify", "not-acceptable"; end;
981 if valid_affiliations[affiliation or "none"] == nil then
982 return nil, "modify", "not-acceptable";
984 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
986 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
987 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
989 if actor ~= true then
990 local actor_affiliation = self:get_affiliation(actor);
991 if actor_affiliation == "owner" then
992 if jid_bare(actor) == jid then -- self change
993 -- need at least one owner
994 local is_last = true;
995 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
997 return nil, "cancel", "conflict";
1000 -- owners can do anything else
1001 elseif affiliation == "owner" or affiliation == "admin"
1002 or actor_affiliation ~= "admin"
1003 or target_affiliation == "owner" or target_affiliation == "admin" then
1004 -- Can't demote owners or other admins
1005 return nil, "cancel", "not-allowed";
1009 -- Set in 'database'
1010 self._affiliations[jid] = affiliation;
1013 local role = self:get_default_role(affiliation);
1014 local role_rank = valid_roles[role or "none"];
1015 local occupants_updated = {}; -- Filled with old roles
1016 for nick, occupant in self:each_occupant() do
1017 if occupant.bare_jid == jid then
1018 -- need to publcize in all cases; as affiliation in <item/> has changed.
1019 occupants_updated[occupant] = occupant.role;
1020 if occupant.role ~= role and (
1022 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1024 occupant.role = role;
1025 self:save_occupant(occupant);
1030 -- Tell the room of the new occupant affiliations+roles
1031 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1032 if not role then -- getting kicked
1033 if affiliation == "outcast" then
1034 x:tag("status", {code="301"}):up(); -- banned
1036 x:tag("status", {code="321"}):up(); -- affiliation change
1039 local is_semi_anonymous = self:get_whois() == "moderators";
1040 for occupant, old_role in pairs(occupants_updated) do
1041 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1042 if is_semi_anonymous and
1043 (old_role == "moderator" and occupant.role ~= "moderator") or
1044 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1045 -- Send everyone else's presences (as jid visibility has changed)
1046 for real_jid in occupant:each_session() do
1047 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1048 return occupant.bare_jid ~= jid;
1054 if self.save then self:save(); end
1056 module:fire_event("muc-set-affiliation", {
1060 affiliation = affiliation or "none";
1062 previous_affiliation = target_affiliation;
1063 in_room = next(occupants_updated) ~= nil;
1069 function room_mt:get_role(nick)
1070 local occupant = self:get_occupant_by_nick(nick);
1071 return occupant and occupant.role or nil;
1074 function room_mt:set_role(actor, occupant_jid, role, reason)
1075 if not actor then return nil, "modify", "not-acceptable"; end
1077 local occupant = self:get_occupant_by_nick(occupant_jid);
1078 if not occupant then return nil, "modify", "not-acceptable"; end
1080 if valid_roles[role or "none"] == nil then
1081 return nil, "modify", "not-acceptable";
1083 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1085 if actor ~= true then
1086 -- Can't do anything to other owners or admins
1087 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1088 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1089 return nil, "cancel", "not-allowed";
1092 -- If you are trying to give or take moderator role you need to be an owner or admin
1093 if occupant.role == "moderator" or role == "moderator" then
1094 local actor_affiliation = self:get_affiliation(actor);
1095 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1096 return nil, "cancel", "not-allowed";
1100 -- Need to be in the room and a moderator
1101 local actor_occupant = self:get_occupant_by_real_jid(actor);
1102 if not actor_occupant or actor_occupant.role ~= "moderator" then
1103 return nil, "cancel", "not-allowed";
1107 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1109 x:tag("status", {code = "307"}):up();
1111 occupant.role = role;
1112 self:save_occupant(occupant);
1113 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1117 local affiliation_notify = module:require "muc/affiliation_notify";
1119 local name = module:require "muc/name";
1120 room_mt.get_name = name.get;
1121 room_mt.set_name = name.set;
1123 local description = module:require "muc/description";
1124 room_mt.get_description = description.get;
1125 room_mt.set_description = description.set;
1127 local hidden = module:require "muc/hidden";
1128 room_mt.get_hidden = hidden.get;
1129 room_mt.set_hidden = hidden.set;
1130 function room_mt:get_public()
1131 return not self:get_hidden();
1133 function room_mt:set_public(public)
1134 return self:set_hidden(not public);
1137 local password = module:require "muc/password";
1138 room_mt.get_password = password.get;
1139 room_mt.set_password = password.set;
1141 local whois = module:require "muc/whois";
1142 room_mt.get_whois = whois.get;
1143 room_mt.set_whois = whois.set;
1145 local members_only = module:require "muc/members_only";
1146 room_mt.get_members_only = members_only.get;
1147 room_mt.set_members_only = members_only.set;
1149 local moderated = module:require "muc/moderated";
1150 room_mt.get_moderated = moderated.get;
1151 room_mt.set_moderated = moderated.set;
1153 local persistent = module:require "muc/persistent";
1154 room_mt.get_persistent = persistent.get;
1155 room_mt.set_persistent = persistent.set;
1157 local subject = module:require "muc/subject";
1158 room_mt.get_changesubject = subject.get_changesubject;
1159 room_mt.set_changesubject = subject.set_changesubject;
1160 room_mt.get_subject = subject.get;
1161 room_mt.set_subject = subject.set;
1162 room_mt.send_subject = subject.send;
1164 local history = module:require "muc/history";
1165 room_mt.send_history = history.send;
1166 room_mt.get_historylength = history.get_length;
1167 room_mt.set_historylength = history.set_length;
1169 local _M = {}; -- module "muc"
1171 function _M.new_room(jid, config)
1172 return setmetatable({
1182 _M.room_mt = room_mt;