Merge 0.10->trunk
[prosody.git] / plugins / muc / muc.lib.lua
index 89953615800fb3667f38d002f28c771585062fb0..75caa233938f49d627df9aefae1c84d2d67935f7 100644 (file)
@@ -13,35 +13,20 @@ local next = next;
 local setmetatable = setmetatable;
 
 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;
+local jid_join = require "util.jid".join;
 local st = require "util.stanza";
 local log = require "util.logger".init("mod_muc");
 local base64 = require "util.encodings".base64;
 local md5 = require "util.hashes".md5;
 
 local occupant_lib = module:require "muc/occupant"
-
-
-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;
@@ -54,32 +39,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
+end);
 
 --- Occupant functions
 function room_mt:new_occupant(bare_real_jid, nick)
@@ -106,6 +80,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
@@ -119,15 +97,25 @@ function room_mt:save_occupant(occupant)
        -- Need to maintain _jid_nick secondary index
        local old_occupant = self._occupants[id];
        if old_occupant then
-               for real_jid in pairs(old_occupant.sessions) do
+               for real_jid in old_occupant:each_session() do
                        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
@@ -136,20 +124,17 @@ 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)
+local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
        x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
-       if actor then
-               x:tag("actor", actor):up()
+       if actor_nick or actor_jid then
+               x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
        end
        if reason then
                x:tag("reason"):text(reason):up()
@@ -159,29 +144,25 @@ local function add_item(x, affiliation, role, jid, nick, actor, reason)
 end
 
 -- actor is (real) jid
-function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
+function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
        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)))};
-       end
        if is_anonymous then
-               add_item(x, affiliation, role, nil, nick, actor_attr, reason);
+               add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
        else
-               if actor_attr then
-                       actor_attr.jid = actor;
-               end
                for real_jid, session in occupant:each_session() do
-                       add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
+                       add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
                end
        end
        return x
 end
 
 function room_mt:broadcast_message(stanza)
-       module:fire_event("muc-broadcast-message", {room = self, stanza = stanza});
+       if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
+               return true;
+       end
        self:broadcast(stanza);
+       return true;
 end
 
 -- Broadcast a stanza to all occupants in the room.
@@ -202,43 +183,79 @@ local function can_see_real_jids(whois, occupant)
        end
 end
 
-local function get_base_presence(occupant)
+-- 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 base_presence;
        if occupant.role ~= nil then
                -- Try to use main jid's presence
                local pr = occupant:get_presence();
                if pr ~= nil then
-                       return st.clone(pr);
+                       base_presence = st.clone(pr);
                end
        end
-       return st.presence {from = occupant.nick; type = "unavailable";};
-end
+       base_presence = base_presence or st.presence {from = occupant.nick; type = "unavailable";};
 
--- 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;
+       -- Fire event (before full_p and anon_p are created)
+       local event = {
+               room = self; stanza = base_presence; x = base_x;
+               occupant = occupant; nick = nick; actor = actor;
+               reason = reason;
+       }
+       module:fire_event("muc-broadcast-presence", event);
+
+       -- Allow muc-broadcast-presence listeners to change things
+       nick = event.nick;
+       actor = event.actor;
+       reason = event.reason;
+
+       local whois = self:get_whois();
+
+       local actor_nick;
+       if actor then
+               actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
        end
-       local full_p, full_x = get_presence(false);
+
+       local full_p, full_x;
+       local function get_full_p()
+               if full_p == nil then
+                       full_x = st.clone(base_x);
+                       self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
+                       full_p = st.clone(base_presence):add_child(full_x);
+               end
+               return full_p, full_x;
+       end
+
        local anon_p, anon_x;
        local function get_anon_p()
                if anon_p == nil then
-                       anon_p, anon_x = get_presence(true);
+                       anon_x = st.clone(base_x);
+                       self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
+                       anon_p = st.clone(base_presence):add_child(anon_x);
                end
                return anon_p, anon_x;
        end
 
-       local whois = self:get_whois();
+       local self_p, self_x;
+       if can_see_real_jids(whois, occupant) then
+               self_p, self_x = get_full_p();
+       else
+               -- Can always see your own full jids
+               -- But not allowed to see actor's
+               self_x = st.clone(base_x);
+               self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
+               self_p = st.clone(base_presence):add_child(self_x);
+       end
 
        -- General populance
        for nick, n_occupant in self:each_occupant() do
                if nick ~= occupant.nick then
                        local pr;
-                       if can_see_real_jids(whois, occupant) or occupant.bare_jid == n_occupant.bare_jid then
-                               pr = full_p;
+                       if can_see_real_jids(whois, n_occupant) then
+                               pr = get_full_p();
+                       elseif occupant.bare_jid == n_occupant.bare_jid then
+                               pr = self_p;
                        else
                                pr = get_anon_p();
                        end
@@ -247,17 +264,16 @@ function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason
        end
 
        -- Presences for occupant itself
-       full_x:tag("status", {code = "110";}):up();
+       self_x:tag("status", {code = "110";}):up();
        if occupant.role == nil then
                -- They get an unavailable
-               self:route_to_occupant(occupant, full_p);
+               self:route_to_occupant(occupant, self_p);
        else
                -- use their own presences as templates
                for full_jid, pr in occupant:each_session() do
                        pr = st.clone(pr);
                        pr.attr.to = full_jid;
-                       -- You can always see your own full jids
-                       pr:add_child(full_x);
+                       pr:add_child(self_x);
                        self:route_stanza(pr);
                end
        end
@@ -265,14 +281,14 @@ end
 
 function room_mt:send_occupant_list(to, filter)
        local to_bare = jid_bare(to);
-       local is_anonymous = true;
+       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 can_see_real_jids(whois, occupant) then
-                               is_anonymous = false;
+                       if not (occupant and can_see_real_jids(whois, occupant)) then
+                               is_anonymous = true;
                        end
                end
        end
@@ -301,19 +317,7 @@ 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)
-       event.reply:tag("feature", {var = event.room:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up();
-end);
-module:hook("muc-disco#info", function(event)
-       event.reply:tag("feature", {var = event.room:get_members_only() and "muc_membersonly" or "muc_open"}):up();
-end);
-module:hook("muc-disco#info", function(event)
-       event.reply:tag("feature", {var = event.room:get_persistent() and "muc_persistent" or "muc_temporary"}):up();
-end);
-module:hook("muc-disco#info", function(event)
-       event.reply:tag("feature", {var = event.room:get_hidden() and "muc_hidden" or "muc_public"}):up();
-end);
-module:hook("muc-disco#info", function(event)
-       local count = 0; for _ in event.room:each_occupant() do count = count + 1; end
+       local count = iterators.count(event.room:each_occupant());
        table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
 end);
 
@@ -325,28 +329,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);
-       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);
@@ -362,64 +344,10 @@ function room_mt:handle_kickable(origin, stanza)
        local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
                :tag("status", {code = "307"})
        self:publicise_occupant_status(occupant, x);
-       return true;
-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
+       if occupant.jid == real_jid then -- Was last session
+               module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
        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;
+       return true;
 end
 
 -- Give the room creator owner affiliation
@@ -427,18 +355,6 @@ module:hook("muc-room-pre-create", function(event)
        event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
 end, -1);
 
--- 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;
@@ -451,20 +367,6 @@ module:hook("muc-occupant-pre-join", function(event)
        end
 end, -10);
 
--- Send occupant list to newly joined user
-module:hook("muc-occupant-joined", function(event)
-       local real_jid = event.stanza.attr.from;
-       event.room:send_occupant_list(real_jid, function(nick, occupant)
-               -- Don't include self
-               return occupant:get_presence(real_jid) == nil;
-       end);
-end, 80);
-
--- Send subject to joining user
-module:hook("muc-occupant-joined", function(event)
-       event.room:send_subject(event.stanza.attr.from);
-end, 20);
-
 function room_mt:handle_presence_to_occupant(origin, stanza)
        local type = stanza.attr.type;
        if type == "error" then -- error, kick em out!
@@ -519,10 +421,14 @@ function room_mt:handle_presence_to_occupant(origin, stanza)
                if orig_occupant == nil then
                        event_name = "muc-occupant-pre-join";
                        event.is_new_room = is_new_room;
+                       event.occupant = dest_occupant;
                elseif dest_occupant == nil then
                        event_name = "muc-occupant-pre-leave";
+                       event.occupant = orig_occupant;
                else
                        event_name = "muc-occupant-pre-change";
+                       event.orig_occupant = orig_occupant;
+                       event.dest_occupant = dest_occupant;
                end
                if module:fire_event(event_name, event) then return true; end
 
@@ -541,6 +447,9 @@ function room_mt:handle_presence_to_occupant(origin, stanza)
                        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);
@@ -578,7 +487,7 @@ function room_mt:handle_presence_to_occupant(origin, stanza)
                        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;});
+                               module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
                        end
                end
 
@@ -592,6 +501,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
@@ -606,8 +523,11 @@ function room_mt:handle_presence_to_occupant(origin, stanza)
                                self:route_stanza(pr);
                        end
 
-                       if orig_occupant == nil and is_first_dest_session then
-                               module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; stanza = stanza;});
+                       if orig_occupant == nil then
+                               if is_first_dest_session then
+                                       module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
+                               end
+                               module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
                        end
                end
        elseif type ~= 'result' then -- bad type
@@ -622,13 +542,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
@@ -637,13 +558,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_occupant_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;
@@ -716,56 +638,21 @@ function room_mt:get_form_layout(actor)
        });
        return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
 end
-module:hook("muc-config-form", function(event)
-       table.insert(event.form, {
-               name = 'muc#roomconfig_persistentroom',
-               type = 'boolean',
-               label = 'Make Room Persistent?',
-               value = event.room:get_persistent()
-       });
-end);
-module:hook("muc-config-form", function(event)
-       table.insert(event.form, {
-               name = 'muc#roomconfig_publicroom',
-               type = 'boolean',
-               label = 'Make Room Publicly Searchable?',
-               value = not event.room:get_hidden()
-       });
-end);
-module:hook("muc-config-form", function(event)
-       table.insert(event.form, {
-               name = 'muc#roomconfig_changesubject',
-               type = 'boolean',
-               label = 'Allow Occupants to Change Subject?',
-               value = event.room:get_changesubject()
-       });
-end);
-module:hook("muc-config-form", function(event)
-       table.insert(event.form, {
-               name = 'muc#roomconfig_moderatedroom',
-               type = 'boolean',
-               label = 'Make Room Moderated?',
-               value = event.room:get_moderated()
-       });
-end);
-module:hook("muc-config-form", function(event)
-       table.insert(event.form, {
-               name = 'muc#roomconfig_membersonly',
-               type = 'boolean',
-               label = 'Make Room Members-Only?',
-               value = event.room:get_members_only()
-       });
-end);
 
 function room_mt:process_form(origin, stanza)
        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;
+               local fields;
+               if form.tags[1] == nil then -- Instant room
+                       fields = {};
+               else
+                       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
                end
 
                local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
@@ -797,21 +684,6 @@ function room_mt:process_form(origin, stanza)
        end
        return true;
 end
-module:hook("muc-config-submitted", function(event)
-       event.update_option("persistent", "muc#roomconfig_persistentroom");
-end);
-module:hook("muc-config-submitted", function(event)
-       event.update_option("moderated", "muc#roomconfig_moderatedroom");
-end);
-module:hook("muc-config-submitted", function(event)
-       event.update_option("members_only", "muc#roomconfig_membersonly");
-end);
-module:hook("muc-config-submitted", function(event)
-       event.update_option("public", "muc#roomconfig_publicroom");
-end);
-module:hook("muc-config-submitted", function(event)
-       event.update_option("changesubject", "muc#roomconfig_changesubject");
-end);
 
 -- Removes everyone from the room
 function room_mt:clear(x)
@@ -824,7 +696,7 @@ function room_mt:clear(x)
        end
        for occupant in pairs(occupants_updated) do
                self:publicise_occupant_status(occupant, x);
-               module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; });
+               module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
        end
 end
 
@@ -836,7 +708,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
 
@@ -886,26 +757,36 @@ function room_mt:handle_admin_query_get_command(origin, stanza)
        local affiliation = self:get_affiliation(actor);
        local item = stanza.tags[1].tags[1];
        local _aff = item.attr.affiliation;
+       local _aff_rank = valid_affiliations[_aff or "none"];
        local _rol = item.attr.role;
-       if _aff and not _rol then
-               if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
+       if _aff and _aff_rank and not _rol then
+               -- You need to be at least an admin, and be requesting info about your affifiliation or lower
+               -- e.g. an admin can't ask for a list of owners
+               local affiliation_rank = valid_affiliations[affiliation];
+               if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
                        local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
-                       for jid, affiliation in pairs(self._affiliations) do
-                               if affiliation == _aff then
-                                       reply:tag("item", {affiliation = _aff, jid = jid}):up();
-                               end
+                       for jid in self:each_affiliation(_aff or "none") do
+                               reply:tag("item", {affiliation = _aff, jid = jid}):up();
                        end
-                       origin.send(reply);
+                       origin.send(reply:up());
                        return true;
                else
                        origin.send(st.error_reply(stanza, "auth", "forbidden"));
                        return true;
                end
-       elseif _rol and not _aff then
+       elseif _rol and valid_roles[_rol or "none"] 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"));
@@ -954,31 +835,26 @@ end
 function room_mt:handle_groupchat_to_room(origin, stanza)
        local from = stanza.attr.from;
        local occupant = self:get_occupant_by_real_jid(from);
-       if not occupant then -- not in room
-               origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
-               return true;
-       elseif occupant.role == "visitor" then
-               origin.send(st.error_reply(stanza, "auth", "forbidden"));
+       if module:fire_event("muc-occupant-groupchat", {
+               room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
+       }) then return true; end
+       stanza.attr.from = occupant.nick;
+       self:broadcast_message(stanza);
+       stanza.attr.from = from;
+       return true;
+end
+
+-- Role check
+module:hook("muc-occupant-groupchat", function(event)
+       local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
+       if role_rank <= valid_roles.none then
+               event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
                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);
-               end
-               stanza.attr.from = from;
+       elseif role_rank <= valid_roles.visitor then
+               event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
                return true;
        end
-end
+end, 50);
 
 -- hack - some buggy clients send presence updates to the room rather than their nick
 function room_mt:handle_presence_to_room(origin, stanza)
@@ -1005,28 +881,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()
@@ -1050,21 +917,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);
-
--- 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
+       if not stanza:get_child("body") then
+               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
 end);
 
@@ -1074,17 +932,23 @@ 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()
                :up();
        if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
-               local occupant = self:get_occupant_by_real_jid(decline.attr.to);
+               local declinee = decline.attr.to; -- re-fetch, in case event modified it
+               local occupant
+               if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
+                       occupant = self:get_occupant_by_nick(declinee);
+               end
                if occupant then
                        self:route_to_occupant(occupant, decline);
                else
@@ -1097,11 +961,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)
@@ -1139,10 +1005,28 @@ function room_mt:get_affiliation(jid)
        return result;
 end
 
+-- Iterates over jid, affiliation pairs
+function room_mt:each_affiliation(with_affiliation)
+       if not with_affiliation then
+               return pairs(self._affiliations);
+       else
+               return function(_affiliations, jid)
+                       local affiliation;
+                       repeat -- Iterate until we get a match
+                               jid, affiliation = next(_affiliations, jid);
+                       until jid == nil or affiliation == with_affiliation
+                       return jid, affiliation;
+               end, self._affiliations, nil
+       end
+end
+
 function room_mt:set_affiliation(actor, jid, affiliation, reason)
        if not actor then return nil, "modify", "not-acceptable"; end;
 
-       jid = jid_bare(jid);
+       local node, host, resource = jid_split(jid);
+       if not host then return nil, "modify", "not-acceptable"; end
+       jid = jid_join(node, host); -- Bare
+       local is_host_only = node == nil;
 
        if valid_affiliations[affiliation or "none"] == nil then
                return nil, "modify", "not-acceptable";
@@ -1152,14 +1036,17 @@ function room_mt:set_affiliation(actor, jid, affiliation, reason)
        local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
        local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
 
-       if actor ~= true then
-               local actor_bare = jid_bare(actor);
-               local actor_affiliation = self._affiliations[actor_bare];
+       if actor == true then
+               actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
+       else
+               local actor_affiliation = self:get_affiliation(actor);
                if actor_affiliation == "owner" then
-                       if actor_bare == jid then -- self change
+                       if jid_bare(actor) == jid then -- self change
                                -- need at least one owner
                                local is_last = true;
-                               for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
+                               for j in self:each_affiliation("owner") do
+                                       if j ~= jid then is_last = false; break; end
+                               end
                                if is_last then
                                        return nil, "cancel", "conflict";
                                end
@@ -1181,7 +1068,10 @@ function room_mt:set_affiliation(actor, jid, affiliation, reason)
        local role_rank = valid_roles[role or "none"];
        local occupants_updated = {}; -- Filled with old roles
        for nick, occupant in self:each_occupant() do
-               if occupant.bare_jid == jid then
+               if occupant.bare_jid == jid or (
+                       -- Outcast can be by host.
+                       is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
+               ) then
                        -- need to publcize in all cases; as affiliation in <item/> has changed.
                        occupants_updated[occupant] = occupant.role;
                        if occupant.role ~= role and (
@@ -1206,7 +1096,9 @@ function room_mt:set_affiliation(actor, jid, affiliation, reason)
        local is_semi_anonymous = self:get_whois() == "moderators";
        for occupant, old_role in pairs(occupants_updated) do
                self:publicise_occupant_status(occupant, x, nil, actor, reason);
-               if is_semi_anonymous and
+               if occupant.role == nil then
+                       module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
+               elseif 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
                        -- Send everyone else's presences (as jid visibility has changed)
@@ -1219,6 +1111,17 @@ function room_mt:set_affiliation(actor, jid, affiliation, reason)
        end
 
        if self.save then self:save(); end
+
+       module:fire_event("muc-set-affiliation", {
+               room = self;
+               actor = actor;
+               jid = jid;
+               affiliation = affiliation or "none";
+               reason = reason;
+               previous_affiliation = target_affiliation;
+               in_room = next(occupants_updated) ~= nil;
+       });
+
        return true;
 end
 
@@ -1238,7 +1141,9 @@ function room_mt:set_role(actor, occupant_jid, role, reason)
        end
        role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
 
-       if actor ~= true then
+       if actor == true then
+               actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
+       else
                -- Can't do anything to other owners or admins
                local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
                if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
@@ -1267,9 +1172,14 @@ function room_mt:set_role(actor, occupant_jid, role, reason)
        occupant.role = role;
        self:save_occupant(occupant);
        self:publicise_occupant_status(occupant, x, nil, actor, reason);
+       if role == nil then
+               module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
+       end
        return true;
 end
 
+local affiliation_notify = module:require "muc/affiliation_notify";
+
 local name = module:require "muc/name";
 room_mt.get_name = name.get;
 room_mt.set_name = name.set;
@@ -1278,6 +1188,16 @@ 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;
@@ -1286,6 +1206,25 @@ 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;
@@ -1293,8 +1232,6 @@ room_mt.set_historylength = history.set_length;
 
 local _M = {}; -- module "muc"
 
-_M.set_max_history_length = history.set_max_length;
-
 function _M.new_room(jid, config)
        return setmetatable({
                jid = jid;