plugins/muc/muc.lib: Don't add invite/decline bodies if they already have one
[prosody.git] / plugins / muc / muc.lib.lua
index c88811781e0dd55e479292fdd1cb4a7caedf949e..57cc3721ef02b5d53e72fb455b736271054bac07 100644 (file)
@@ -11,13 +11,9 @@ local select = select;
 local pairs, ipairs = pairs, ipairs;
 local next = next;
 local setmetatable = setmetatable;
-local t_insert, t_remove = table.insert, table.remove;
-
-local gettime = os.time;
-local datetime = require "util.datetime";
 
 local dataform = require "util.dataforms";
-
+local iterators = require "util.iterators";
 local jid_split = require "util.jid".split;
 local jid_bare = require "util.jid".bare;
 local jid_prep = require "util.jid".prep;
@@ -27,27 +23,9 @@ local base64 = require "util.encodings".base64;
 local md5 = require "util.hashes".md5;
 
 local occupant_lib = module:require "muc/occupant"
-
-local default_history_length, max_history_length = 20, math.huge;
-
-local is_kickable_error do
-       local kickable_error_conditions = {
-               ["gone"] = true;
-               ["internal-server-error"] = true;
-               ["item-not-found"] = true;
-               ["jid-malformed"] = true;
-               ["recipient-unavailable"] = true;
-               ["redirect"] = true;
-               ["remote-server-not-found"] = true;
-               ["remote-server-timeout"] = true;
-               ["service-unavailable"] = true;
-               ["malformed error"] = true;
-       };
-       function is_kickable_error(stanza)
-               local cond = select(2, stanza:get_error()) or "malformed error";
-               return kickable_error_conditions[cond];
-       end
-end
+local muc_util = module:require "muc/util";
+local is_kickable_error = muc_util.is_kickable_error;
+local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
 
 local room_mt = {};
 room_mt.__index = room_mt;
@@ -60,43 +38,21 @@ function room_mt:get_occupant_jid(real_jid)
        return self._jid_nick[real_jid]
 end
 
-local valid_affiliations = {
-       outcast = 0;
-       none = 1;
-       member = 2;
-       admin = 3;
-       owner = 4;
-};
-
-local valid_roles = {
-       none = 0;
-       visitor = 1;
-       participant = 2;
-       moderator = 3;
-};
-
 function room_mt:get_default_role(affiliation)
-       if affiliation == "owner" or affiliation == "admin" then
+       local role = module:fire_event("muc-get-default-role", {
+               room = self;
+               affiliation = affiliation;
+               affiliation_rank = valid_affiliations[affiliation or "none"];
+       });
+       return role, valid_roles[role or "none"];
+end
+module:hook("muc-get-default-role", function(event)
+       if event.affiliation_rank >= valid_affiliations.admin then
                return "moderator";
-       elseif affiliation == "member" then
+       elseif event.affiliation_rank >= valid_affiliations.none then
                return "participant";
-       elseif not affiliation then
-               if not self:get_members_only() then
-                       return self:get_moderated() and "visitor" or "participant";
-               end
        end
-end
-
-function room_mt:lock()
-       self.locked = true
-end
-function room_mt:unlock()
-       module:fire_event("muc-room-unlocked", { room = self });
-       self.locked = nil
-end
-function room_mt:is_locked()
-       return not not self.locked
-end
+end);
 
 --- Occupant functions
 function room_mt:new_occupant(bare_real_jid, nick)
@@ -123,6 +79,10 @@ do
        end
 end
 
+function room_mt:has_occupant()
+       return next(self._occupants, nil) ~= nil
+end
+
 function room_mt:get_occupant_by_real_jid(real_jid)
        local occupant_jid = self:get_occupant_jid(real_jid);
        if occupant_jid == nil then return nil end
@@ -140,11 +100,21 @@ function room_mt:save_occupant(occupant)
                        self._jid_nick[real_jid] = nil;
                end
        end
-       if occupant.role ~= nil and next(occupant.sessions) then
+
+       local has_live_session = false
+       if occupant.role ~= nil then
                for real_jid, presence in occupant:each_session() do
-                       self._jid_nick[real_jid] = occupant.nick;
+                       if presence.attr.type == nil then
+                               has_live_session = true
+                               self._jid_nick[real_jid] = occupant.nick;
+                       end
                end
-       else
+               if not has_live_session then
+                       -- Has no live sessions left; they have left the room.
+                       occupant.role = nil
+               end
+       end
+       if not has_live_session then
                occupant = nil
        end
        self._occupants[id] = occupant
@@ -153,15 +123,12 @@ end
 function room_mt:route_to_occupant(occupant, stanza)
        local to = stanza.attr.to;
        for jid, pr in occupant:each_session() do
-               if pr.attr.type ~= "unavailable" then
-                       stanza.attr.to = jid;
-                       self:route_stanza(stanza);
-               end
+               stanza.attr.to = jid;
+               self:route_stanza(stanza);
        end
        stanza.attr.to = to;
 end
 
--- Adds an item to an "x" element.
 -- actor is the attribute table
 local function add_item(x, affiliation, role, jid, nick, actor, reason)
        x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
@@ -174,10 +141,11 @@ local function add_item(x, affiliation, role, jid, nick, actor, reason)
        x:up();
        return x
 end
+
 -- actor is (real) jid
 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
-       local affiliation = self:get_affiliation(occupant.bare_jid);
-       local role = occupant.role;
+       local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
+       local role = occupant.role or "none";
        local actor_attr;
        if actor then
                actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
@@ -195,29 +163,11 @@ function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
        return x
 end
 
-function room_mt:broadcast_message(stanza, historic)
-       module:fire_event("muc-broadcast-message", {room = self, stanza = stanza, historic = historic});
+function room_mt:broadcast_message(stanza)
+       module:fire_event("muc-broadcast-message", {room = self, stanza = stanza});
        self:broadcast(stanza);
 end
 
--- add to history
-module:hook("muc-broadcast-message", function(event)
-       if event.historic then
-               local room = event.room
-               local history = room._data['history'];
-               if not history then history = {}; room._data['history'] = history; end
-               local stanza = st.clone(event.stanza);
-               stanza.attr.to = "";
-               local ts = gettime();
-               local stamp = datetime.datetime(ts);
-               stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = module.host, stamp = stamp}):up(); -- XEP-0203
-               stanza:tag("x", {xmlns = "jabber:x:delay", from = module.host, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
-               local entry = { stanza = stanza, timestamp = ts };
-               t_insert(history, entry);
-               while #history > room:get_historylength() do t_remove(history, 1) end
-       end
-end);
-
 -- Broadcast a stanza to all occupants in the room.
 -- optionally checks conditional called with (nick, occupant)
 function room_mt:broadcast(stanza, cond_func)
@@ -228,41 +178,56 @@ function room_mt:broadcast(stanza, cond_func)
        end
 end
 
--- Broadcasts an occupant's presence to the whole room
--- Takes (and modifies) the x element that goes into the stanzas
-function room_mt:publicise_occupant_status(occupant, full_x, actor, reason)
-       local anon_x;
-       local has_anonymous = self:get_whois() ~= "anyone";
-       if has_anonymous then
-               anon_x = st.clone(full_x);
-               self:build_item_list(occupant, anon_x, true, nil, actor, reason);
+local function can_see_real_jids(whois, occupant)
+       if whois == "anyone" then
+               return true;
+       elseif whois == "moderators" then
+               return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
        end
-       self:build_item_list(occupant,full_x, false, nil, actor, reason);
+end
 
-       -- General populance
-       local full_p
+local function get_base_presence(occupant)
        if occupant.role ~= nil then
                -- Try to use main jid's presence
                local pr = occupant:get_presence();
                if pr ~= nil then
-                       full_p = st.clone(pr);
+                       return st.clone(pr);
                end
        end
-       if full_p == nil then
-               full_p = st.presence{from=occupant.nick; type="unavailable"};
-       end
-       local anon_p;
-       if has_anonymous then
-               anon_p = st.clone(full_p);
-               anon_p:add_child(anon_x);
+       return st.presence {from = occupant.nick; type = "unavailable";};
+end
+
+-- Broadcasts an occupant's presence to the whole room
+-- Takes the x element that goes into the stanzas
+function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
+       -- Build real jid and (optionally) occupant jid template presences
+       local function get_presence(is_anonymous)
+               local x = st.clone(base_x);
+               self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
+               return get_base_presence(occupant):add_child(x), x;
+       end
+       local full_p, full_x = get_presence(false);
+
+       module:fire_event("muc-broadcast-presence", {room = self; stanza = full_p; x = full_x;});
+
+       local anon_p, anon_x;
+       local function get_anon_p()
+               if anon_p == nil then
+                       anon_p, anon_x = get_presence(true);
+               end
+               return anon_p, anon_x;
        end
-       full_p:add_child(full_x);
 
+       local whois = self:get_whois();
+
+       -- General populance
        for nick, n_occupant in self:each_occupant() do
-               if nick ~= occupant.nick or n_occupant.role == nil then
-                       local pr = full_p;
-                       if has_anonymous and n_occupant.role ~= "moderator" and occupant.bare_jid ~= n_occupant.bare_jid then
-                               pr = anon_p;
+               if nick ~= occupant.nick then
+                       local pr;
+                       if can_see_real_jids(whois, n_occupant) or occupant.bare_jid == n_occupant.bare_jid then
+                               pr = full_p;
+                       else
+                               pr = get_anon_p();
                        end
                        self:route_to_occupant(n_occupant, pr);
                end
@@ -276,26 +241,25 @@ function room_mt:publicise_occupant_status(occupant, full_x, actor, reason)
        else
                -- use their own presences as templates
                for full_jid, pr in occupant:each_session() do
-                       if pr.attr.type ~= "unavailable" then
-                               pr = st.clone(pr);
-                               pr.attr.to = full_jid;
-                               -- You can always see your own full jids
-                               pr:add_child(full_x);
-                               self:route_stanza(pr);
-                       end
+                       pr = st.clone(pr);
+                       pr.attr.to = full_jid;
+                       -- You can always see your own full jids
+                       pr:add_child(full_x);
+                       self:route_stanza(pr);
                end
        end
 end
 
 function room_mt:send_occupant_list(to, filter)
        local to_bare = jid_bare(to);
-       local is_anonymous = true;
-       if self:get_whois() ~= "anyone" then
+       local is_anonymous = false;
+       local whois = self:get_whois();
+       if whois ~= "anyone" then
                local affiliation = self:get_affiliation(to);
                if affiliation ~= "admin" and affiliation ~= "owner" then
                        local occupant = self:get_occupant_by_real_jid(to);
-                       if not occupant or occupant.role ~= "moderator" then
-                               is_anonymous = false;
+                       if not (occupant and can_see_real_jids(whois, occupant)) then
+                               is_anonymous = true;
                        end
                end
        end
@@ -311,108 +275,23 @@ function room_mt:send_occupant_list(to, filter)
        end
 end
 
-local function parse_history(stanza)
-       local x_tag = stanza:get_child("x", "http://jabber.org/protocol/muc");
-       local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
-       if not history_tag then
-               return nil, 20, nil
-       end
-
-       local maxchars = tonumber(history_tag.attr.maxchars);
-
-       local maxstanzas = tonumber(history_tag.attr.maxstanzas);
-
-       -- messages received since the UTC datetime specified
-       local since = history_tag.attr.since;
-       if since then
-               since = datetime.parse(since);
-       end
-
-       -- messages received in the last "X" seconds.
-       local seconds = tonumber(history_tag.attr.seconds);
-       if seconds then
-               seconds = gettime() - seconds
-               if since then
-                       since = math.max(since, seconds);
-               else
-                       since = seconds;
-               end
-       end
-
-       return maxchars, maxstanzas, since
+function room_mt:get_disco_info(stanza)
+       local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
+       local form = dataform.new {
+               { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
+       };
+       module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
+       reply:add_child(form:form(nil, "result"));
+       return reply;
 end
-
-module:hook("muc-get-history", function(event)
-       local room = event.room
-       local history = room._data['history']; -- send discussion history
-       if not history then return nil end
-       local history_len = #history
-
-       local to = event.to
-       local maxchars = event.maxchars
-       local maxstanzas = event.maxstanzas or history_len
-       local since = event.since
-       local n = 0;
-       local charcount = 0;
-       for i=history_len,1,-1 do
-               local entry = history[i];
-               if maxchars then
-                       if not entry.chars then
-                               entry.stanza.attr.to = "";
-                               entry.chars = #tostring(entry.stanza);
-                       end
-                       charcount = charcount + entry.chars + #to;
-                       if charcount > maxchars then break; end
-               end
-               if since and since > entry.timestamp then break; end
-               if n + 1 > maxstanzas then break; end
-               n = n + 1;
-       end
-
-       local i = history_len-n+1
-       function event:next_stanza()
-               if i > history_len then return nil end
-               local entry = history[i]
-               local msg = entry.stanza
-               msg.attr.to = to;
-               i = i + 1
-               return msg
-       end
-       return true;
+module:hook("muc-disco#info", function(event)
+       event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
+end);
+module:hook("muc-disco#info", function(event)
+       local count = iterators.count(event.room:each_occupant());
+       table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
 end);
 
-function room_mt:send_history(stanza)
-       local maxchars, maxstanzas, since = parse_history(stanza)
-       local event = {
-               room = self;
-               to = stanza.attr.from; -- `to` is required to calculate the character count for `maxchars`
-               maxchars = maxchars, maxstanzas = maxstanzas, since = since;
-               next_stanza = function() end; -- events should define this iterator
-       }
-       module:fire_event("muc-get-history", event)
-       for msg in event.next_stanza , event do
-               self:route_stanza(msg);
-       end
-end
-
-function room_mt:get_disco_info(stanza)
-       local count = 0; for _ in self:each_occupant() do count = count + 1; end
-       return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
-               :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
-               :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
-               :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
-               :tag("feature", {var=self:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
-               :tag("feature", {var=self:get_members_only() and "muc_membersonly" or "muc_open"}):up()
-               :tag("feature", {var=self:get_persistent() and "muc_persistent" or "muc_temporary"}):up()
-               :tag("feature", {var=self:get_hidden() and "muc_hidden" or "muc_public"}):up()
-               :tag("feature", {var=self:get_whois() ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
-               :add_child(dataform.new({
-                       { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
-                       { name = "muc#roominfo_description", label = "Description", value = "" },
-                       { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) }
-               }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
-       ;
-end
 function room_mt:get_disco_items(stanza)
        local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
        for room_jid in self:each_occupant() do
@@ -421,28 +300,6 @@ function room_mt:get_disco_items(stanza)
        return reply;
 end
 
-function room_mt:get_subject()
-       return self._data['subject'], self._data['subject_from']
-end
-local function create_subject_message(from, subject)
-       return st.message({from = from; type = "groupchat"})
-               :tag('subject'):text(subject):up();
-end
-function room_mt:send_subject(to)
-       local msg = create_subject_message(self:get_subject());
-       msg.attr.to = to;
-       self:route_stanza(msg);
-end
-function room_mt:set_subject(current_nick, subject)
-       if subject == "" then subject = nil; end
-       self._data['subject'] = subject;
-       self._data['subject_from'] = current_nick;
-       if self.save then self:save(); end
-       local msg = create_subject_message(current_nick, subject);
-       self:broadcast_message(msg, false);
-       return true;
-end
-
 function room_mt:handle_kickable(origin, stanza)
        local real_jid = stanza.attr.from;
        local occupant = self:get_occupant_by_real_jid(real_jid);
@@ -461,163 +318,11 @@ function room_mt:handle_kickable(origin, stanza)
        return true;
 end
 
-function room_mt:set_name(name)
-       if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
-       if self._data.name ~= name then
-               self._data.name = name;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_name()
-       return self._data.name or jid_split(self.jid);
-end
-function room_mt:set_description(description)
-       if description == "" or type(description) ~= "string" then description = nil; end
-       if self._data.description ~= description then
-               self._data.description = description;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_description()
-       return self._data.description;
-end
-function room_mt:set_password(password)
-       if password == "" or type(password) ~= "string" then password = nil; end
-       if self._data.password ~= password then
-               self._data.password = password;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_password()
-       return self._data.password;
-end
-function room_mt:set_moderated(moderated)
-       moderated = moderated and true or nil;
-       if self._data.moderated ~= moderated then
-               self._data.moderated = moderated;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_moderated()
-       return self._data.moderated;
-end
-function room_mt:set_members_only(members_only)
-       members_only = members_only and true or nil;
-       if self._data.members_only ~= members_only then
-               self._data.members_only = members_only;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_members_only()
-       return self._data.members_only;
-end
-function room_mt:set_persistent(persistent)
-       persistent = persistent and true or nil;
-       if self._data.persistent ~= persistent then
-               self._data.persistent = persistent;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_persistent()
-       return self._data.persistent;
-end
-function room_mt:set_hidden(hidden)
-       hidden = hidden and true or nil;
-       if self._data.hidden ~= hidden then
-               self._data.hidden = hidden;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_hidden()
-       return self._data.hidden;
-end
-function room_mt:get_public()
-       return not self:get_hidden();
-end
-function room_mt:set_public(public)
-       return self:set_hidden(not public);
-end
-function room_mt:set_changesubject(changesubject)
-       changesubject = changesubject and true or nil;
-       if self._data.changesubject ~= changesubject then
-               self._data.changesubject = changesubject;
-               if self.save then self:save(true); end
-       end
-end
-function room_mt:get_changesubject()
-       return self._data.changesubject;
-end
-function room_mt:get_historylength()
-       return self._data.history_length or default_history_length;
-end
-function room_mt:set_historylength(length)
-       length = math.min(tonumber(length) or default_history_length, max_history_length or math.huge);
-       if length == default_history_length then
-               length = nil;
-       end
-       self._data.history_length = length;
-end
-
-
-local valid_whois = { moderators = true, anyone = true };
-
-function room_mt:set_whois(whois)
-       if valid_whois[whois] and self._data.whois ~= whois then
-               self._data.whois = whois;
-               if self.save then self:save(true); end
-       end
-end
-
-function room_mt:get_whois()
-       return self._data.whois;
-end
-
-module:hook("muc-room-pre-create", function(event)
-       local room = event.room;
-       if room:is_locked() and not event.stanza:get_child("x", "http://jabber.org/protocol/muc") then
-               room:unlock(); -- Older groupchat protocol doesn't lock
-       end
-end, 10);
-
 -- Give the room creator owner affiliation
 module:hook("muc-room-pre-create", function(event)
        event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
 end, -1);
 
-module:hook("muc-occupant-pre-join", function(event)
-       local room, stanza = event.room, event.stanza;
-       local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
-       password = password and password:get_child_text("password", "http://jabber.org/protocol/muc");
-       if not password or password == "" then password = nil; end
-       if room:get_password() ~= password then
-               local from, to = stanza.attr.from, stanza.attr.to;
-               log("debug", "%s couldn't join due to invalid password: %s", from, to);
-               local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
-               reply.tags[1].attr.code = "401";
-               event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
-               return true;
-       end
-end, -20);
-
-module:hook("muc-occupant-pre-join", function(event)
-       if event.room:is_locked() then -- Deny entry
-               event.origin.send(st.error_reply(event.stanza, "cancel", "item-not-found"));
-               return true;
-       end
-end, -30);
-
--- registration required for entering members-only room
-module:hook("muc-occupant-pre-join", function(event)
-       local room, stanza = event.room, event.stanza;
-       local affiliation = room:get_affiliation(stanza.attr.from);
-       if affiliation == nil and event.room:get_members_only() then
-               local reply = st.error_reply(stanza, "auth", "registration-required"):up();
-               reply.tags[1].attr.code = "407";
-               event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
-               return true;
-       end
-end, -5);
-
 -- check if user is banned
 module:hook("muc-occupant-pre-join", function(event)
        local room, stanza = event.room, event.stanza;
@@ -630,17 +335,6 @@ module:hook("muc-occupant-pre-join", function(event)
        end
 end, -10);
 
-module:hook("muc-occupant-joined", function(event)
-       local room, stanza = event.room, event.stanza;
-       local real_jid = stanza.attr.from;
-       room:send_occupant_list(real_jid, function(nick, occupant)
-               -- Don't include self
-               return occupant:get_presence(real_jid) == nil;
-       end);
-       room:send_history(stanza);
-       room:send_subject(real_jid);
-end, -1);
-
 function room_mt:handle_presence_to_occupant(origin, stanza)
        local type = stanza.attr.type;
        if type == "error" then -- error, kick em out!
@@ -714,46 +408,47 @@ function room_mt:handle_presence_to_occupant(origin, stanza)
                -- Send presence stanza about original occupant
                if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
                        local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
-
+                       local dest_nick;
                        if dest_occupant == nil then -- Session is leaving
                                log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
+                               if is_last_orig_session then
+                                       orig_occupant.role = nil;
+                               end
                                orig_occupant:set_session(real_jid, stanza);
                        else
                                log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
-                               orig_occupant:remove_session(real_jid); -- If we are moving to a new nick; we don't want to get our own presence
-
-                               local dest_nick = select(3, jid_split(dest_occupant.nick));
-                               local affiliation = self:get_affiliation(bare_jid);
-
-                               -- This session
+                               local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
+                               orig_occupant:set_session(real_jid, generated_unavail);
+                               dest_nick = select(3, jid_split(dest_occupant.nick));
                                if not is_first_dest_session then -- User is swapping into another pre-existing session
                                        log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
                                        -- Show the other session leaving
                                        local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
                                                :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
-                                       add_item(x, affiliation, "none");
+                                       add_item(x, self:get_affiliation(bare_jid), "none");
                                        local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
                                                :add_child(x);
                                        self:route_stanza(pr);
-                               else
-                                       if is_last_orig_session then -- User is moving to a new session
-                                               log("debug", "no sessions in %s left; marking as nick change", orig_occupant.nick);
-                                               -- Everyone gets to see this as a nick change
-                                               local jid = self:get_whois() ~= "anyone" and real_jid or nil; -- FIXME: mods should see real jids
-                                               add_item(orig_x, affiliation, orig_occupant.role, jid, dest_nick);
-                                               orig_x:tag("status", {code = "303";}):up();
-                                       end
                                end
-                               -- The session itself always sees a nick change
-                               local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
-                               add_item(x, affiliation, orig_occupant.role, real_jid, dest_nick);
-                               -- self:build_item_list(orig_occupant, x, false); -- COMPAT
-                               x:tag("status", {code = "303";}):up();
-                               x:tag("status", {code = "110";}):up();
-                               self:route_stanza(st.presence{from = orig_occupant.nick, to = real_jid, type = "unavailable"}:add_child(x));
+                               if is_first_dest_session and is_last_orig_session then -- Normal nick change
+                                       log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
+                                       orig_x:tag("status", {code = "303";}):up();
+                               else -- The session itself always needs to see a nick change
+                                       -- don't want to get our old nick's available presence,
+                                       -- so remove our session from there, and manually generate an unavailable
+                                       orig_occupant:remove_session(real_jid);
+                                       log("debug", "generating nick change for %s", real_jid);
+                                       local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
+                                       -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
+                                       add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
+                                       x:tag("status", {code = "303";}):up();
+                                       x:tag("status", {code = "110";}):up();
+                                       self:route_stanza(generated_unavail:add_child(x));
+                                       dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
+                               end
                        end
                        self:save_occupant(orig_occupant);
-                       self:publicise_occupant_status(orig_occupant, orig_x);
+                       self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
 
                        if is_last_orig_session then
                                module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick;});
@@ -770,6 +465,14 @@ function room_mt:handle_presence_to_occupant(origin, stanza)
                                dest_x:tag("status", {code = "100"}):up();
                        end
                        self:save_occupant(dest_occupant);
+
+                       if orig_occupant == nil then
+                               -- Send occupant list to newly joined user
+                               self:send_occupant_list(real_jid, function(nick, occupant)
+                                       -- Don't include self
+                                       return occupant:get_presence(real_jid) == nil;
+                               end)
+                       end
                        self:publicise_occupant_status(dest_occupant, dest_x);
 
                        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
@@ -800,13 +503,14 @@ function room_mt:handle_iq_to_occupant(origin, stanza)
        local from, to = stanza.attr.from, stanza.attr.to;
        local type = stanza.attr.type;
        local id = stanza.attr.id;
-       local current_nick = self:get_occupant_jid(from);
        local occupant = self:get_occupant_by_nick(to);
        if (type == "error" or type == "result") then
                do -- deconstruct_stanza_id
-                       if not current_nick or not occupant then return nil; end
+                       if not occupant then return nil; end
                        local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
                        if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
+                       local from_occupant_jid = self:get_occupant_jid(from_jid);
+                       if from_occupant_jid == nil then return nil; end
                        local session_jid
                        for to_jid in occupant:each_session() do
                                if md5(to_jid) == to_jid_hash then
@@ -815,13 +519,14 @@ function room_mt:handle_iq_to_occupant(origin, stanza)
                                end
                        end
                        if session_jid == nil then return nil; end
-                       stanza.attr.from, stanza.attr.to, stanza.attr.id = current_nick, session_jid, id
+                       stanza.attr.from, stanza.attr.to, stanza.attr.id = from_jid, session_jid, id;
                end
                log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
                self:route_stanza(stanza);
                stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
                return true;
        else -- Type is "get" or "set"
+               local current_nick = self:get_occupant_jid(from);
                if not current_nick then
                        origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
                        return true;
@@ -883,7 +588,6 @@ function room_mt:send_form(origin, stanza)
 end
 
 function room_mt:get_form_layout(actor)
-       local whois = self:get_whois()
        local form = dataform.new({
                title = "Configuration for "..self.jid,
                instructions = "Complete and submit this form to configure the room.",
@@ -891,127 +595,50 @@ function room_mt:get_form_layout(actor)
                        name = 'FORM_TYPE',
                        type = 'hidden',
                        value = 'http://jabber.org/protocol/muc#roomconfig'
-               },
-               {
-                       name = 'muc#roomconfig_roomname',
-                       type = 'text-single',
-                       label = 'Name',
-                       value = self:get_name() or "",
-               },
-               {
-                       name = 'muc#roomconfig_roomdesc',
-                       type = 'text-single',
-                       label = 'Description',
-                       value = self:get_description() or "",
-               },
-               {
-                       name = 'muc#roomconfig_persistentroom',
-                       type = 'boolean',
-                       label = 'Make Room Persistent?',
-                       value = self:get_persistent()
-               },
-               {
-                       name = 'muc#roomconfig_publicroom',
-                       type = 'boolean',
-                       label = 'Make Room Publicly Searchable?',
-                       value = not self:get_hidden()
-               },
-               {
-                       name = 'muc#roomconfig_changesubject',
-                       type = 'boolean',
-                       label = 'Allow Occupants to Change Subject?',
-                       value = self:get_changesubject()
-               },
-               {
-                       name = 'muc#roomconfig_whois',
-                       type = 'list-single',
-                       label = 'Who May Discover Real JIDs?',
-                       value = {
-                               { value = 'moderators', label = 'Moderators Only', default = whois == 'moderators' },
-                               { value = 'anyone',     label = 'Anyone',          default = whois == 'anyone' }
-                       }
-               },
-               {
-                       name = 'muc#roomconfig_roomsecret',
-                       type = 'text-private',
-                       label = 'Password',
-                       value = self:get_password() or "",
-               },
-               {
-                       name = 'muc#roomconfig_moderatedroom',
-                       type = 'boolean',
-                       label = 'Make Room Moderated?',
-                       value = self:get_moderated()
-               },
-               {
-                       name = 'muc#roomconfig_membersonly',
-                       type = 'boolean',
-                       label = 'Make Room Members-Only?',
-                       value = self:get_members_only()
-               },
-               {
-                       name = 'muc#roomconfig_historylength',
-                       type = 'text-single',
-                       label = 'Maximum Number of History Messages Returned by Room',
-                       value = tostring(self:get_historylength())
                }
        });
        return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
 end
 
 function room_mt:process_form(origin, stanza)
-       local query = stanza.tags[1];
-       local form = query:get_child("x", "jabber:x:data")
-       if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
-       if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
-       if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
-
-       local fields = self:get_form_layout(stanza.attr.from):data(form);
-       if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration")); return; end
-
-
-       local changed = {};
+       local form = stanza.tags[1]:get_child("x", "jabber:x:data");
+       if form.attr.type == "cancel" then
+               origin.send(st.reply(stanza));
+       elseif form.attr.type == "submit" then
+               local fields = self:get_form_layout(stanza.attr.from):data(form);
+               if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
+                       origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
+                       return true;
+               end
 
-       local function handle_option(name, field, allowed)
-               local new = fields[field];
-               if new == nil then return; end
-               if allowed and not allowed[new] then return; end
-               if new == self["get_"..name](self) then return; end
-               changed[name] = true;
-               self["set_"..name](self, new);
-       end
+               local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
+               function event.update_option(name, field, allowed)
+                       local new = fields[field];
+                       if new == nil then return; end
+                       if allowed and not allowed[new] then return; end
+                       if new == self["get_"..name](self) then return; end
+                       event.status_codes["104"] = true;
+                       self["set_"..name](self, new);
+                       return true;
+               end
+               module:fire_event("muc-config-submitted", event);
 
-       local event = { room = self, fields = fields, changed = changed, stanza = stanza, origin = origin, update_option = handle_option };
-       module:fire_event("muc-config-submitted", event);
-
-       handle_option("name", "muc#roomconfig_roomname");
-       handle_option("description", "muc#roomconfig_roomdesc");
-       handle_option("persistent", "muc#roomconfig_persistentroom");
-       handle_option("moderated", "muc#roomconfig_moderatedroom");
-       handle_option("members_only", "muc#roomconfig_membersonly");
-       handle_option("public", "muc#roomconfig_publicroom");
-       handle_option("changesubject", "muc#roomconfig_changesubject");
-       handle_option("historylength", "muc#roomconfig_historylength");
-       handle_option("whois", "muc#roomconfig_whois", valid_whois);
-       handle_option("password", "muc#roomconfig_roomsecret");
-
-       if self.save then self:save(true); end
-       if self:is_locked() then
-               self:unlock();
-       end
-       origin.send(st.reply(stanza));
+               if self.save then self:save(true); end
+               origin.send(st.reply(stanza));
 
-       if next(changed) then
-               local msg = st.message({type='groupchat', from=self.jid})
-                       :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
-                               :tag('status', {code = '104'}):up()
-                       :up();
-               if changed.whois then
-                       local code = (self:get_whois() == 'moderators') and "173" or "172";
-                       msg.tags[1]:tag('status', {code = code}):up();
+               if next(event.status_codes) then
+                       local msg = st.message({type='groupchat', from=self.jid})
+                               :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
+                       for code in pairs(event.status_codes) do
+                               msg:tag("status", {code = code;}):up();
+                       end
+                       msg:up();
+                       self:broadcast_message(msg);
                end
-               self:broadcast_message(msg, false)
+       else
+               origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
        end
+       return true;
 end
 
 -- Removes everyone from the room
@@ -1037,7 +664,6 @@ function room_mt:destroy(newjid, reason, password)
        if password then x:tag("password"):text(password):up(); end
        x:up();
        self:clear(x);
-       self:set_persistent(false);
        module:fire_event("muc-room-destroyed", { room = self });
 end
 
@@ -1104,9 +730,17 @@ function room_mt:handle_admin_query_get_command(origin, stanza)
                end
        elseif _rol and not _aff then
                local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
-               if role == "moderator" then
+               if valid_roles[role or "none"] >= valid_roles.moderator then
                        if _rol == "none" then _rol = nil; end
-                       self:send_occupant_list(actor, function(occupant_jid, occupant) return occupant.role == _rol end);
+                       local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
+                       -- TODO: whois check here? (though fully anonymous rooms are not supported)
+                       for occupant_jid, occupant in self:each_occupant() do
+                               if occupant.role == _rol then
+                                       local nick = select(3,jid_split(occupant_jid));
+                                       self:build_item_list(occupant, reply, false, nick);
+                               end
+                       end
+                       origin.send(reply:up());
                        return true;
                else
                        origin.send(st.error_reply(stanza, "auth", "forbidden"));
@@ -1144,13 +778,20 @@ function room_mt:handle_owner_query_set_to_room(origin, stanza)
                self:destroy(newjid, reason, password);
                origin.send(st.reply(stanza));
                return true;
+       elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
+               return self:process_form(origin, stanza);
        else
-               self:process_form(origin, stanza);
+               origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
                return true;
        end
 end
 
 function room_mt:handle_groupchat_to_room(origin, stanza)
+       -- Prosody has made the decision that messages with <subject/> are exclusively subject changes
+       -- e.g. body will be ignored; even if the subject change was not allowed
+       if stanza:get_child("subject") then
+               return module:fire_event("muc-subject-change", {room = self, origin = origin, stanza = stanza});
+       end
        local from = stanza.attr.from;
        local occupant = self:get_occupant_by_real_jid(from);
        if not occupant then -- not in room
@@ -1159,24 +800,11 @@ function room_mt:handle_groupchat_to_room(origin, stanza)
        elseif occupant.role == "visitor" then
                origin.send(st.error_reply(stanza, "auth", "forbidden"));
                return true;
-       else
-               local from = stanza.attr.from;
-               stanza.attr.from = occupant.nick;
-               local subject = stanza:get_child_text("subject");
-               if subject then
-                       if occupant.role == "moderator" or
-                               ( self:get_changesubject() and occupant.role == "participant" ) then -- and participant
-                               self:set_subject(occupant.nick, subject);
-                       else
-                               stanza.attr.from = from;
-                               origin.send(st.error_reply(stanza, "auth", "forbidden"));
-                       end
-               else
-                       self:broadcast_message(stanza, self:get_historylength() > 0 and stanza:get_child("body"));
-               end
-               stanza.attr.from = from;
-               return true;
        end
+       stanza.attr.from = occupant.nick;
+       self:broadcast_message(stanza);
+       stanza.attr.from = from;
+       return true;
 end
 
 -- hack - some buggy clients send presence updates to the room rather than their nick
@@ -1204,28 +832,19 @@ module:hook("muc-pre-invite", function(event)
        end
 end);
 
--- Invitation privileges in members-only rooms SHOULD be restricted to room admins;
--- if a member without privileges to edit the member list attempts to invite another user
--- the service SHOULD return a <forbidden/> error to the occupant
-module:hook("muc-pre-invite", function(event)
-       local room, stanza = event.room, event.stanza;
-       if room:get_members_only() and valid_affiliations[room:get_affiliation(stanza.attr.from) or "none"] < valid_affiliations.admin then
-               event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
-               return true;
-       end
-end);
-
 function room_mt:handle_mediated_invite(origin, stanza)
        local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
        local invitee = jid_prep(payload.attr.to);
        if not invitee then
                origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
                return true;
-       elseif not module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
+       elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
                return true;
        end
-       local invite = st.message({from = self.jid, to = invitee, id = stanza.attr.id})
-               :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
+       local invite = muc_util.filter_muc_x(st.clone(stanza));
+       invite.attr.from = self.jid;
+       invite.attr.to = invitee;
+       invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
                        :tag('invite', {from = stanza.attr.from;})
                                :tag('reason'):text(payload:get_child_text("reason")):up()
                        :up()
@@ -1236,15 +855,6 @@ function room_mt:handle_mediated_invite(origin, stanza)
        return true;
 end
 
--- Add password to outgoing invite
-module:hook("muc-invite", function(event)
-       local password = event.room:get_password();
-       if password then
-               local x = event.stanza:get_child("x", "http://jabber.org/protocol/muc#user");
-               x:tag("password"):text(password):up();
-       end
-end);
-
 -- COMPAT: Some older clients expect this
 module:hook("muc-invite", function(event)
        local room, stanza = event.room, event.stanza;
@@ -1258,33 +868,12 @@ end);
 -- Add a plain message for clients which don't support invites
 module:hook("muc-invite", function(event)
        local room, stanza = event.room, event.stanza;
-       local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
-       local reason = invite:get_child_text("reason") or "";
-       stanza:tag("body")
-               :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
-       :up();
-end);
-
--- Mask 'from' jid as occupant jid if room is anonymous
-module:hook("muc-invite", function(event)
-       local room, stanza = event.room, event.stanza;
-       if room:get_whois() == "moderators" and room:get_default_role(room:get_affiliation(stanza.attr.to)) ~= "moderator" then
+       if not stanza:get_child("body") then
                local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
-               local occupant_jid = room:get_occupant_jid(invite.attr.from);
-               if occupant_jid ~= nil then -- FIXME: This will expose real jid if inviter is not in room
-                       invite.attr.from = occupant_jid;
-               end
-       end
-end, 50);
-
--- When an invite is sent; add an affiliation for the invitee
-module:hook("muc-invite", function(event)
-       local room, stanza = event.room, event.stanza
-       local invitee = stanza.attr.to
-       if room:get_members_only() and not room:get_affiliation(invitee) then
-               local from = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite").attr.from
-               log("debug", "%s invited %s into members only room %s, granting membership", from, invitee, room.jid);
-               room:set_affiliation(from, invitee, "member", "Invited by " .. from); -- This might fail; ignore for now
+               local reason = invite:get_child_text("reason") or "";
+               stanza:tag("body")
+                       :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
+               :up();
        end
 end);
 
@@ -1294,11 +883,13 @@ function room_mt:handle_mediated_decline(origin, stanza)
        if not declinee then
                origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
                return true;
-       elseif not module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
+       elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
                return true;
        end
-       local decline = st.message({from = self.jid, to = declinee, id = stanza.attr.id})
-               :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
+       local decline = muc_util.filter_muc_x(st.clone(stanza));
+       decline.attr.from = self.jid;
+       decline.attr.to = declinee;
+       decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
                        :tag("decline", {from = stanza.attr.from})
                                :tag("reason"):text(payload:get_child_text("reason")):up()
                        :up()
@@ -1317,11 +908,13 @@ end
 -- Add a plain message for clients which don't support declines
 module:hook("muc-decline", function(event)
        local room, stanza = event.room, event.stanza;
-       local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
-       local reason = decline:get_child_text("reason") or "";
-       stanza:tag("body")
-               :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
-       :up();
+       if not stanza:get_child("body") then
+               local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
+               local reason = decline:get_child_text("reason") or "";
+               stanza:tag("body")
+                       :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
+               :up();
+       end
 end);
 
 function room_mt:handle_message_to_room(origin, stanza)
@@ -1425,7 +1018,7 @@ function room_mt:set_affiliation(actor, jid, affiliation, reason)
        end
        local is_semi_anonymous = self:get_whois() == "moderators";
        for occupant, old_role in pairs(occupants_updated) do
-               self:publicise_occupant_status(occupant, x, actor, reason);
+               self:publicise_occupant_status(occupant, x, nil, actor, reason);
                if is_semi_anonymous and
                        (old_role == "moderator" and occupant.role ~= "moderator") or
                        (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
@@ -1486,31 +1079,73 @@ function room_mt:set_role(actor, occupant_jid, role, reason)
        end
        occupant.role = role;
        self:save_occupant(occupant);
-       self:publicise_occupant_status(occupant, x, actor, reason);
+       self:publicise_occupant_status(occupant, x, nil, actor, reason);
        return true;
 end
 
+local name = module:require "muc/name";
+room_mt.get_name = name.get;
+room_mt.set_name = name.set;
+
+local description = module:require "muc/description";
+room_mt.get_description = description.get;
+room_mt.set_description = description.set;
+
+local hidden = module:require "muc/hidden";
+room_mt.get_hidden = hidden.get;
+room_mt.set_hidden = hidden.set;
+function room_mt:get_public()
+       return not self:get_hidden();
+end
+function room_mt:set_public(public)
+       return self:set_hidden(not public);
+end
+
+local password = module:require "muc/password";
+room_mt.get_password = password.get;
+room_mt.set_password = password.set;
+
+local whois = module:require "muc/whois";
+room_mt.get_whois = whois.get;
+room_mt.set_whois = whois.set;
+
+local members_only = module:require "muc/members_only";
+room_mt.get_members_only = members_only.get;
+room_mt.set_members_only = members_only.set;
+
+local moderated = module:require "muc/moderated";
+room_mt.get_moderated = moderated.get;
+room_mt.set_moderated = moderated.set;
+
+local persistent = module:require "muc/persistent";
+room_mt.get_persistent = persistent.get;
+room_mt.set_persistent = persistent.set;
+
+local subject = module:require "muc/subject";
+room_mt.get_changesubject = subject.get_changesubject;
+room_mt.set_changesubject = subject.set_changesubject;
+room_mt.get_subject = subject.get;
+room_mt.set_subject = subject.set;
+room_mt.send_subject = subject.send;
+
+local history = module:require "muc/history";
+room_mt.send_history = history.send;
+room_mt.get_historylength = history.get_length;
+room_mt.set_historylength = history.set_length;
+
 local _M = {}; -- module "muc"
 
 function _M.new_room(jid, config)
        return setmetatable({
                jid = jid;
-               locked = nil;
                _jid_nick = {};
                _occupants = {};
                _data = {
-                   whois = 'moderators';
-                   history_length = math.min((config and config.history_length)
-                       or default_history_length, max_history_length);
                };
                _affiliations = {};
        }, room_mt);
 end
 
-function _M.set_max_history_length(_max_history_length)
-       max_history_length = _max_history_length or math.huge;
-end
-
 _M.room_mt = room_mt;
 
 return _M;