dde1e13f6e1d7c91d4dd21f9172127613010f82d
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- Copyright (C) 2014 Daurnimator
5 --
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9
10 local select = select;
11 local pairs = pairs;
12 local next = next;
13 local setmetatable = setmetatable;
14
15 local dataform = require "util.dataforms";
16 local iterators = require "util.iterators";
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local jid_join = require "util.jid".join;
21 local st = require "util.stanza";
22 local base64 = require "util.encodings".base64;
23 local md5 = require "util.hashes".md5;
24
25 local log = module._log;
26
27 local occupant_lib = module:require "muc/occupant"
28 local muc_util = module:require "muc/util";
29 local is_kickable_error = muc_util.is_kickable_error;
30 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
31
32 local room_mt = {};
33 room_mt.__index = room_mt;
34
35 function room_mt:__tostring()
36         return "MUC room ("..self.jid..")";
37 end
38
39 function room_mt.save()
40         -- overriden by mod_muc.lua
41 end
42
43 function room_mt:get_occupant_jid(real_jid)
44         return self._jid_nick[real_jid]
45 end
46
47 function room_mt:get_default_role(affiliation)
48         local role = module:fire_event("muc-get-default-role", {
49                 room = self;
50                 affiliation = affiliation;
51                 affiliation_rank = valid_affiliations[affiliation or "none"];
52         });
53         return role, valid_roles[role or "none"];
54 end
55 module:hook("muc-get-default-role", function(event)
56         if event.affiliation_rank >= valid_affiliations.admin then
57                 return "moderator";
58         elseif event.affiliation_rank >= valid_affiliations.none then
59                 return "participant";
60         end
61 end);
62
63 --- Occupant functions
64 function room_mt:new_occupant(bare_real_jid, nick)
65         local occupant = occupant_lib.new(bare_real_jid, nick);
66         local affiliation = self:get_affiliation(bare_real_jid);
67         occupant.role = self:get_default_role(affiliation);
68         return occupant;
69 end
70
71 function room_mt:get_occupant_by_nick(nick)
72         local occupant = self._occupants[nick];
73         if occupant == nil then return nil end
74         return occupant_lib.copy(occupant);
75 end
76
77 do
78         local function next_copied_occupant(occupants, occupant_jid)
79                 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
80                 if next_occupant_jid == nil then return nil end
81                 return next_occupant_jid, occupant_lib.copy(raw_occupant);
82         end
83         -- FIXME Explain what 'read_only' is supposed to be
84         function room_mt:each_occupant(read_only) -- luacheck: ignore 212
85                 return next_copied_occupant, self._occupants, nil;
86         end
87 end
88
89 function room_mt:has_occupant()
90         return next(self._occupants, nil) ~= nil
91 end
92
93 function room_mt:get_occupant_by_real_jid(real_jid)
94         local occupant_jid = self:get_occupant_jid(real_jid);
95         if occupant_jid == nil then return nil end
96         return self:get_occupant_by_nick(occupant_jid);
97 end
98
99 function room_mt:save_occupant(occupant)
100         occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
101         local id = occupant.nick
102
103         -- Need to maintain _jid_nick secondary index
104         local old_occupant = self._occupants[id];
105         if old_occupant then
106                 for real_jid in old_occupant:each_session() do
107                         self._jid_nick[real_jid] = nil;
108                 end
109         end
110
111         local has_live_session = false
112         if occupant.role ~= nil then
113                 for real_jid, presence in occupant:each_session() do
114                         if presence.attr.type == nil then
115                                 has_live_session = true
116                                 self._jid_nick[real_jid] = occupant.nick;
117                         end
118                 end
119                 if not has_live_session then
120                         -- Has no live sessions left; they have left the room.
121                         occupant.role = nil
122                 end
123         end
124         if not has_live_session then
125                 occupant = nil
126         end
127         self._occupants[id] = occupant
128 end
129
130 function room_mt:route_to_occupant(occupant, stanza)
131         local to = stanza.attr.to;
132         for jid in occupant:each_session() do
133                 stanza.attr.to = jid;
134                 self:route_stanza(stanza);
135         end
136         stanza.attr.to = to;
137 end
138
139 -- actor is the attribute table
140 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
141         x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
142         if actor_nick or actor_jid then
143                 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
144         end
145         if reason then
146                 x:tag("reason"):text(reason):up()
147         end
148         x:up();
149         return x
150 end
151
152 -- actor is (real) jid
153 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
154         local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
155         local role = occupant.role or "none";
156         if is_anonymous then
157                 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
158         else
159                 for real_jid in occupant:each_session() do
160                         add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
161                 end
162         end
163         return x
164 end
165
166 function room_mt:broadcast_message(stanza)
167         if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
168                 return true;
169         end
170         self:broadcast(stanza);
171         return true;
172 end
173
174 -- Broadcast a stanza to all occupants in the room.
175 -- optionally checks conditional called with (nick, occupant)
176 function room_mt:broadcast(stanza, cond_func)
177         for nick, occupant in self:each_occupant() do
178                 if cond_func == nil or cond_func(nick, occupant) then
179                         self:route_to_occupant(occupant, stanza)
180                 end
181         end
182 end
183
184 local function can_see_real_jids(whois, occupant)
185         if whois == "anyone" then
186                 return true;
187         elseif whois == "moderators" then
188                 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
189         end
190 end
191
192 -- Broadcasts an occupant's presence to the whole room
193 -- Takes the x element that goes into the stanzas
194 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
195         -- Build real jid and (optionally) occupant jid template presences
196         local base_presence do
197                 -- Try to use main jid's presence
198                 local pr = occupant:get_presence();
199                 if pr and (pr.attr.type ~= "unavailable" and occupant.role ~= nil) then
200                         base_presence = st.clone(pr);
201                 else -- user is leaving but didn't send a leave presence. make one for them
202                         base_presence = st.presence {from = occupant.nick; type = "unavailable";};
203                 end
204         end
205
206         -- Fire event (before full_p and anon_p are created)
207         local event = {
208                 room = self; stanza = base_presence; x = base_x;
209                 occupant = occupant; nick = nick; actor = actor;
210                 reason = reason;
211         }
212         module:fire_event("muc-broadcast-presence", event);
213
214         -- Allow muc-broadcast-presence listeners to change things
215         nick = event.nick;
216         actor = event.actor;
217         reason = event.reason;
218
219         local whois = self:get_whois();
220
221         local actor_nick;
222         if actor then
223                 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
224         end
225
226         local full_p, full_x;
227         local function get_full_p()
228                 if full_p == nil then
229                         full_x = st.clone(base_x);
230                         self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
231                         full_p = st.clone(base_presence):add_child(full_x);
232                 end
233                 return full_p, full_x;
234         end
235
236         local anon_p, anon_x;
237         local function get_anon_p()
238                 if anon_p == nil then
239                         anon_x = st.clone(base_x);
240                         self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
241                         anon_p = st.clone(base_presence):add_child(anon_x);
242                 end
243                 return anon_p, anon_x;
244         end
245
246         local self_p, self_x;
247         if can_see_real_jids(whois, occupant) then
248                 self_p, self_x = get_full_p();
249         else
250                 -- Can always see your own full jids
251                 -- But not allowed to see actor's
252                 self_x = st.clone(base_x);
253                 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
254                 self_p = st.clone(base_presence):add_child(self_x);
255         end
256
257         -- General populance
258         for occupant_nick, n_occupant in self:each_occupant() do
259                 if occupant_nick ~= occupant.nick then
260                         local pr;
261                         if can_see_real_jids(whois, n_occupant) then
262                                 pr = get_full_p();
263                         elseif occupant.bare_jid == n_occupant.bare_jid then
264                                 pr = self_p;
265                         else
266                                 pr = get_anon_p();
267                         end
268                         self:route_to_occupant(n_occupant, pr);
269                 end
270         end
271
272         -- Presences for occupant itself
273         self_x:tag("status", {code = "110";}):up();
274         if occupant.role == nil then
275                 -- They get an unavailable
276                 self:route_to_occupant(occupant, self_p);
277         else
278                 -- use their own presences as templates
279                 for full_jid, pr in occupant:each_session() do
280                         pr = st.clone(pr);
281                         pr.attr.to = full_jid;
282                         pr:add_child(self_x);
283                         self:route_stanza(pr);
284                 end
285         end
286 end
287
288 function room_mt:send_occupant_list(to, filter)
289         local to_bare = jid_bare(to);
290         local is_anonymous = false;
291         local whois = self:get_whois();
292         if whois ~= "anyone" then
293                 local affiliation = self:get_affiliation(to);
294                 if affiliation ~= "admin" and affiliation ~= "owner" then
295                         local occupant = self:get_occupant_by_real_jid(to);
296                         if not (occupant and can_see_real_jids(whois, occupant)) then
297                                 is_anonymous = true;
298                         end
299                 end
300         end
301         for occupant_jid, occupant in self:each_occupant() do
302                 if filter == nil or filter(occupant_jid, occupant) then
303                         local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
304                         self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
305                         local pres = st.clone(occupant:get_presence());
306                         pres.attr.to = to;
307                         pres:add_child(x);
308                         self:route_stanza(pres);
309                 end
310         end
311 end
312
313 function room_mt:get_disco_info(stanza)
314         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
315         local form = dataform.new {
316                 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
317         };
318         local formdata = {};
319         module:fire_event("muc-disco#info", {room = self; reply = reply; form = form, formdata = formdata ;});
320         reply:add_child(form:form(formdata, "result"));
321         return reply;
322 end
323 module:hook("muc-disco#info", function(event)
324         event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
325 end);
326 module:hook("muc-disco#info", function(event)
327         table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants" });
328         event.formdata["muc#roominfo_occupants"] = tostring(iterators.count(event.room:each_occupant()));
329 end);
330
331 function room_mt:get_disco_items(stanza)
332         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
333         for room_jid in self:each_occupant() do
334                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
335         end
336         return reply;
337 end
338
339 function room_mt:handle_kickable(origin, stanza) -- luacheck: ignore 212
340         local real_jid = stanza.attr.from;
341         local occupant = self:get_occupant_by_real_jid(real_jid);
342         if occupant == nil then return nil; end
343         local type, condition, text = stanza:get_error();
344         local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
345         if text then
346                 error_message = error_message..": "..text;
347         end
348         occupant:set_session(real_jid, st.presence({type="unavailable"})
349                 :tag('status'):text(error_message));
350         self:save_occupant(occupant);
351         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
352                 :tag("status", {code = "307"})
353         self:publicise_occupant_status(occupant, x);
354         if occupant.jid == real_jid then -- Was last session
355                 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
356         end
357         return true;
358 end
359
360 if not module:get_option_boolean("muc_compat_create", true) then
361         module:hook("muc-room-pre-create", function(event)
362                 local origin, stanza = event.origin, event.stanza;
363                 if not stanza:get_child("x", "http://jabber.org/protocol/muc") then
364                         origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
365                         return true;
366                 end
367         end, -1);
368 end
369
370 -- Give the room creator owner affiliation
371 module:hook("muc-room-pre-create", function(event)
372         event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
373 end, -1);
374
375 -- check if user is banned
376 module:hook("muc-occupant-pre-join", function(event)
377         local room, stanza = event.room, event.stanza;
378         local affiliation = room:get_affiliation(stanza.attr.from);
379         if affiliation == "outcast" then
380                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
381                 reply.tags[1].attr.code = "403";
382                 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
383                 return true;
384         end
385 end, -10);
386
387 function room_mt:handle_presence_to_occupant(origin, stanza)
388         local type = stanza.attr.type;
389         if type == "error" then -- error, kick em out!
390                 return self:handle_kickable(origin, stanza)
391         elseif type == nil or type == "unavailable" then
392                 local real_jid = stanza.attr.from;
393                 local bare_jid = jid_bare(real_jid);
394                 local orig_occupant, dest_occupant;
395                 local is_new_room = next(self._affiliations) == nil;
396                 if is_new_room then
397                         if type == "unavailable" then return true; end -- Unavailable from someone not in the room
398                         if module:fire_event("muc-room-pre-create", {
399                                         room = self;
400                                         origin = origin;
401                                         stanza = stanza;
402                                 }) then return true; end
403                 else
404                         orig_occupant = self:get_occupant_by_real_jid(real_jid);
405                         if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
406                 end
407                 local is_first_dest_session;
408                 if type == "unavailable" then -- luacheck: ignore 542
409                         -- FIXME Why the empty if branch?
410                         -- dest_occupant = nil
411                 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
412                         log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
413                         dest_occupant = orig_occupant;
414                 else
415                         local dest_jid = stanza.attr.to;
416                         dest_occupant = self:get_occupant_by_nick(dest_jid);
417                         if dest_occupant == nil then
418                                 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
419                                 is_first_dest_session = true;
420                                 dest_occupant = self:new_occupant(bare_jid, dest_jid);
421                         else
422                                 is_first_dest_session = false;
423                         end
424                 end
425                 local is_last_orig_session;
426                 if orig_occupant ~= nil then
427                         -- Is there are least 2 sessions?
428                         local iter, ob, last = orig_occupant:each_session();
429                         is_last_orig_session = iter(ob, iter(ob, last)) == nil;
430                 end
431
432                 -- TODO Handle these cases sensibly
433                 local muc_x = stanza:get_child("x", "http://jabber.org/protocol/muc");
434                 if orig_occupant == nil and not muc_x then
435                         module:log("debug", "Join without <x>, possibly desynced");
436                 elseif orig_occupant ~= nil and muc_x then
437                         module:log("debug", "Presence update with <x>, possibly desynced");
438                 end
439
440                 local event, event_name = {
441                         room = self;
442                         origin = origin;
443                         stanza = stanza;
444                         is_first_session = is_first_dest_session;
445                         is_last_session = is_last_orig_session;
446                 };
447                 if orig_occupant == nil then
448                         event_name = "muc-occupant-pre-join";
449                         event.is_new_room = is_new_room;
450                         event.occupant = dest_occupant;
451                 elseif dest_occupant == nil then
452                         event_name = "muc-occupant-pre-leave";
453                         event.occupant = orig_occupant;
454                 else
455                         event_name = "muc-occupant-pre-change";
456                         event.orig_occupant = orig_occupant;
457                         event.dest_occupant = dest_occupant;
458                 end
459                 if module:fire_event(event_name, event) then return true; end
460
461                 -- Check for nick conflicts
462                 if dest_occupant ~= nil and not is_first_dest_session and bare_jid ~= jid_bare(dest_occupant.bare_jid) then -- new nick or has different bare real jid
463                         log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
464                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
465                         reply.tags[1].attr.code = "409";
466                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
467                         return true;
468                 end
469
470                 -- Send presence stanza about original occupant
471                 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
472                         local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
473                         local dest_nick;
474                         if dest_occupant == nil then -- Session is leaving
475                                 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
476                                 if is_last_orig_session then
477                                         orig_occupant.role = nil;
478                                 end
479                                 orig_occupant:set_session(real_jid, stanza);
480                         else
481                                 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
482                                 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
483                                 orig_occupant:set_session(real_jid, generated_unavail);
484                                 dest_nick = select(3, jid_split(dest_occupant.nick));
485                                 if not is_first_dest_session then -- User is swapping into another pre-existing session
486                                         log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
487                                         -- Show the other session leaving
488                                         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
489                                                 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
490                                         add_item(x, self:get_affiliation(bare_jid), "none");
491                                         local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
492                                                 :add_child(x);
493                                         self:route_stanza(pr);
494                                 end
495                                 if is_first_dest_session and is_last_orig_session then -- Normal nick change
496                                         log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
497                                         orig_x:tag("status", {code = "303";}):up();
498                                 else -- The session itself always needs to see a nick change
499                                         -- don't want to get our old nick's available presence,
500                                         -- so remove our session from there, and manually generate an unavailable
501                                         orig_occupant:remove_session(real_jid);
502                                         log("debug", "generating nick change for %s", real_jid);
503                                         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
504                                         -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
505                                         add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
506                                         x:tag("status", {code = "303";}):up();
507                                         x:tag("status", {code = "110";}):up();
508                                         self:route_stanza(generated_unavail:add_child(x));
509                                         dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
510                                 end
511                         end
512                         self:save_occupant(orig_occupant);
513                         self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
514
515                         if is_last_orig_session then
516                                 module:fire_event("muc-occupant-left", {
517                                         room = self;
518                                         nick = orig_occupant.nick;
519                                         occupant = orig_occupant;
520                                         origin = origin;
521                                         stanza = stanza;
522                                 });
523                         end
524                 end
525
526                 if dest_occupant ~= nil then
527                         dest_occupant:set_session(real_jid, stanza);
528                         local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
529                         if is_new_room then
530                                 dest_x:tag("status", {code = "201"}):up();
531                         end
532                         if orig_occupant == nil and self:get_whois() == "anyone" then
533                                 dest_x:tag("status", {code = "100"}):up();
534                         end
535                         self:save_occupant(dest_occupant);
536
537                         if orig_occupant == nil then
538                                 -- Send occupant list to newly joined user
539                                 self:send_occupant_list(real_jid, function(nick, occupant) -- luacheck: ignore 212
540                                         -- Don't include self
541                                         return occupant:get_presence(real_jid) == nil;
542                                 end)
543                         end
544                         self:publicise_occupant_status(dest_occupant, dest_x);
545
546                         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
547                                 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
548                                 -- Show the original nick joining again
549                                 local pr = st.clone(orig_occupant:get_presence());
550                                 pr.attr.to = real_jid;
551                                 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
552                                 self:build_item_list(orig_occupant, x, false);
553                                 -- TODO: new status code to inform client this was the multi-session it left?
554                                 pr:add_child(x);
555                                 self:route_stanza(pr);
556                         end
557
558                         if orig_occupant == nil then
559                                 if is_first_dest_session then
560                                         module:fire_event("muc-occupant-joined", {
561                                                 room = self;
562                                                 nick = dest_occupant.nick;
563                                                 occupant = dest_occupant;
564                                                 stanza = stanza;
565                                                 origin = origin;
566                                         });
567                                 end
568                                 module:fire_event("muc-occupant-session-new", {
569                                         room = self;
570                                         nick = dest_occupant.nick;
571                                         occupant = dest_occupant;
572                                         stanza = stanza;
573                                         origin = origin;
574                                         jid = real_jid;
575                                 });
576                         end
577                 end
578         elseif type ~= 'result' then -- bad type
579                 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
580                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
581                 end
582         end
583         return true;
584 end
585
586 function room_mt:handle_iq_to_occupant(origin, stanza)
587         local from, to = stanza.attr.from, stanza.attr.to;
588         local type = stanza.attr.type;
589         local id = stanza.attr.id;
590         local occupant = self:get_occupant_by_nick(to);
591         if (type == "error" or type == "result") then
592                 do -- deconstruct_stanza_id
593                         if not occupant then return nil; end
594                         local from_jid, orig_id, to_jid_hash = (base64.decode(id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
595                         if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
596                         local from_occupant_jid = self:get_occupant_jid(from_jid);
597                         if from_occupant_jid == nil then return nil; end
598                         local session_jid
599                         for to_jid in occupant:each_session() do
600                                 if md5(to_jid) == to_jid_hash then
601                                         session_jid = to_jid;
602                                         break;
603                                 end
604                         end
605                         if session_jid == nil then return nil; end
606                         stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, orig_id;
607                 end
608                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
609                 self:route_stanza(stanza);
610                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
611                 return true;
612         else -- Type is "get" or "set"
613                 local current_nick = self:get_occupant_jid(from);
614                 if not current_nick then
615                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
616                         return true;
617                 end
618                 if not occupant then -- recipient not in room
619                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
620                         return true;
621                 end
622                 do -- construct_stanza_id
623                         stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
624                 end
625                 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
626                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
627                 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
628                         stanza.attr.to = jid_bare(stanza.attr.to);
629                 end
630                 self:route_stanza(stanza);
631                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
632                 return true;
633         end
634 end
635
636 function room_mt:handle_message_to_occupant(origin, stanza)
637         local from, to = stanza.attr.from, stanza.attr.to;
638         local current_nick = self:get_occupant_jid(from);
639         local type = stanza.attr.type;
640         if not current_nick then -- not in room
641                 if type ~= "error" then
642                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
643                 end
644                 return true;
645         end
646         if type == "groupchat" then -- groupchat messages not allowed in PM
647                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
648                 return true;
649         elseif type == "error" and is_kickable_error(stanza) then
650                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
651                 return self:handle_kickable(origin, stanza); -- send unavailable
652         end
653
654         local o_data = self:get_occupant_by_nick(to);
655         if not o_data then
656                 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
657                 return true;
658         end
659         log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
660         stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
661         stanza.attr.from = current_nick;
662         self:route_to_occupant(o_data, stanza)
663         -- TODO: Remove x tag?
664         stanza.attr.from = from;
665         return true;
666 end
667
668 function room_mt:send_form(origin, stanza)
669         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
670                 :add_child(self:get_form_layout(stanza.attr.from):form())
671         );
672 end
673
674 function room_mt:get_form_layout(actor)
675         local form = dataform.new({
676                 title = "Configuration for "..self.jid,
677                 instructions = "Complete and submit this form to configure the room.",
678                 {
679                         name = 'FORM_TYPE',
680                         type = 'hidden',
681                         value = 'http://jabber.org/protocol/muc#roomconfig'
682                 }
683         });
684         return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
685 end
686
687 function room_mt:process_form(origin, stanza)
688         local form = stanza.tags[1]:get_child("x", "jabber:x:data");
689         if form.attr.type == "cancel" then
690                 origin.send(st.reply(stanza));
691         elseif form.attr.type == "submit" then
692                 local fields, errors, present;
693                 if form.tags[1] == nil then -- Instant room
694                         fields, present = {}, {};
695                 else
696                         fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
697                         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
698                                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
699                                 return true;
700                         end
701                 end
702
703                 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
704                 function event.update_option(name, field, allowed)
705                         local new = fields[field];
706                         if new == nil then return; end
707                         if allowed and not allowed[new] then return; end
708                         if new == self["get_"..name](self) then return; end
709                         event.status_codes["104"] = true;
710                         self["set_"..name](self, new);
711                         return true;
712                 end
713                 module:fire_event("muc-config-submitted", event);
714                 for submitted_field in pairs(present) do
715                         event.field, event.value = submitted_field, fields[submitted_field];
716                         module:fire_event("muc-config-submitted/"..submitted_field, event);
717                 end
718                 event.field, event.value = nil, nil;
719
720                 self:save();
721                 origin.send(st.reply(stanza));
722
723                 if next(event.status_codes) then
724                         local msg = st.message({type='groupchat', from=self.jid})
725                                 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
726                         for code in pairs(event.status_codes) do
727                                 msg:tag("status", {code = code;}):up();
728                         end
729                         msg:up();
730                         self:broadcast_message(msg);
731                 end
732         else
733                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
734         end
735         return true;
736 end
737
738 -- Removes everyone from the room
739 function room_mt:clear(x)
740         x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
741         local occupants_updated = {};
742         for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
743                 occupant.role = nil;
744                 self:save_occupant(occupant);
745                 occupants_updated[occupant] = true;
746         end
747         for occupant in pairs(occupants_updated) do
748                 self:publicise_occupant_status(occupant, x);
749                 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
750         end
751 end
752
753 function room_mt:destroy(newjid, reason, password)
754         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
755                 :tag("item", { affiliation='none', role='none' }):up()
756                 :tag("destroy", {jid=newjid});
757         if reason then x:tag("reason"):text(reason):up(); end
758         if password then x:tag("password"):text(password):up(); end
759         x:up();
760         self:clear(x);
761         module:fire_event("muc-room-destroyed", { room = self });
762 end
763
764 function room_mt:handle_disco_info_get_query(origin, stanza)
765         origin.send(self:get_disco_info(stanza));
766         return true;
767 end
768
769 function room_mt:handle_disco_items_get_query(origin, stanza)
770         origin.send(self:get_disco_items(stanza));
771         return true;
772 end
773
774 function room_mt:handle_admin_query_set_command(origin, stanza)
775         local item = stanza.tags[1].tags[1];
776         if not item then
777                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
778         end
779         if item.attr.jid then -- Validate provided JID
780                 item.attr.jid = jid_prep(item.attr.jid);
781                 if not item.attr.jid then
782                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
783                         return true;
784                 end
785         end
786         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
787                 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
788                 if occupant then item.attr.jid = occupant.jid; end
789         elseif not item.attr.nick and item.attr.jid then
790                 local nick = self:get_occupant_jid(item.attr.jid);
791                 if nick then item.attr.nick = select(3, jid_split(nick)); end
792         end
793         local actor = stanza.attr.from;
794         local reason = item:get_child_text("reason");
795         local success, errtype, err
796         if item.attr.affiliation and item.attr.jid and not item.attr.role then
797                 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
798         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
799                 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
800         else
801                 success, errtype, err = nil, "cancel", "bad-request";
802         end
803         self:save();
804         if not success then
805                 origin.send(st.error_reply(stanza, errtype, err));
806         else
807                 origin.send(st.reply(stanza));
808         end
809         return true;
810 end
811
812 function room_mt:handle_admin_query_get_command(origin, stanza)
813         local actor = stanza.attr.from;
814         local affiliation = self:get_affiliation(actor);
815         local item = stanza.tags[1].tags[1];
816         local _aff = item.attr.affiliation;
817         local _aff_rank = valid_affiliations[_aff or "none"];
818         local _rol = item.attr.role;
819         if _aff and _aff_rank and not _rol then
820                 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
821                 -- e.g. an admin can't ask for a list of owners
822                 local affiliation_rank = valid_affiliations[affiliation or "none"];
823                 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
824                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
825                         for jid in self:each_affiliation(_aff or "none") do
826                                 reply:tag("item", {affiliation = _aff, jid = jid}):up();
827                         end
828                         origin.send(reply:up());
829                         return true;
830                 else
831                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
832                         return true;
833                 end
834         elseif _rol and valid_roles[_rol or "none"] and not _aff then
835                 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
836                 if valid_roles[role or "none"] >= valid_roles.moderator then
837                         if _rol == "none" then _rol = nil; end
838                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
839                         -- TODO: whois check here? (though fully anonymous rooms are not supported)
840                         for occupant_jid, occupant in self:each_occupant() do
841                                 if occupant.role == _rol then
842                                         local nick = select(3,jid_split(occupant_jid));
843                                         self:build_item_list(occupant, reply, false, nick);
844                                 end
845                         end
846                         origin.send(reply:up());
847                         return true;
848                 else
849                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
850                         return true;
851                 end
852         else
853                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
854                 return true;
855         end
856 end
857
858 function room_mt:handle_owner_query_get_to_room(origin, stanza)
859         if self:get_affiliation(stanza.attr.from) ~= "owner" then
860                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
861                 return true;
862         end
863
864         self:send_form(origin, stanza);
865         return true;
866 end
867 function room_mt:handle_owner_query_set_to_room(origin, stanza)
868         if self:get_affiliation(stanza.attr.from) ~= "owner" then
869                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
870                 return true;
871         end
872
873         local child = stanza.tags[1].tags[1];
874         if not child then
875                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
876                 return true;
877         elseif child.name == "destroy" then
878                 local newjid = child.attr.jid;
879                 local reason = child:get_child_text("reason");
880                 local password = child:get_child_text("password");
881                 self:destroy(newjid, reason, password);
882                 origin.send(st.reply(stanza));
883                 return true;
884         elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
885                 return self:process_form(origin, stanza);
886         else
887                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
888                 return true;
889         end
890 end
891
892 function room_mt:handle_groupchat_to_room(origin, stanza)
893         local from = stanza.attr.from;
894         local occupant = self:get_occupant_by_real_jid(from);
895         if module:fire_event("muc-occupant-groupchat", {
896                 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
897         }) then return true; end
898         stanza.attr.from = occupant.nick;
899         self:broadcast_message(stanza);
900         stanza.attr.from = from;
901         return true;
902 end
903
904 -- Role check
905 module:hook("muc-occupant-groupchat", function(event)
906         local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
907         if role_rank <= valid_roles.none then
908                 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
909                 return true;
910         elseif role_rank <= valid_roles.visitor then
911                 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
912                 return true;
913         end
914 end, 50);
915
916 -- hack - some buggy clients send presence updates to the room rather than their nick
917 function room_mt:handle_presence_to_room(origin, stanza)
918         local current_nick = self:get_occupant_jid(stanza.attr.from);
919         local handled
920         if current_nick then
921                 local to = stanza.attr.to;
922                 stanza.attr.to = current_nick;
923                 handled = self:handle_presence_to_occupant(origin, stanza);
924                 stanza.attr.to = to;
925         end
926         return handled;
927 end
928
929 -- Need visitor role or higher to invite
930 module:hook("muc-pre-invite", function(event)
931         local room, stanza = event.room, event.stanza;
932         local _from = stanza.attr.from;
933         local inviter = room:get_occupant_by_real_jid(_from);
934         local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
935         if valid_roles[role or "none"] <= valid_roles.visitor then
936                 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
937                 return true;
938         end
939 end);
940
941 function room_mt:handle_mediated_invite(origin, stanza)
942         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
943         local invitee = jid_prep(payload.attr.to);
944         if not invitee then
945                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
946                 return true;
947         elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
948                 return true;
949         end
950         local invite = muc_util.filter_muc_x(st.clone(stanza));
951         invite.attr.from = self.jid;
952         invite.attr.to = invitee;
953         invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
954                         :tag('invite', {from = stanza.attr.from;})
955                                 :tag('reason'):text(payload:get_child_text("reason")):up()
956                         :up()
957                 :up();
958         if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
959                 self:route_stanza(invite);
960         end
961         return true;
962 end
963
964 -- COMPAT: Some older clients expect this
965 module:hook("muc-invite", function(event)
966         local room, stanza = event.room, event.stanza;
967         local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
968         local reason = invite:get_child_text("reason");
969         stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
970                 :text(reason or "")
971         :up();
972 end);
973
974 -- Add a plain message for clients which don't support invites
975 module:hook("muc-invite", function(event)
976         local room, stanza = event.room, event.stanza;
977         if not stanza:get_child("body") then
978                 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
979                 local reason = invite:get_child_text("reason") or "";
980                 stanza:tag("body")
981                         :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
982                 :up();
983         end
984 end);
985
986 function room_mt:handle_mediated_decline(origin, stanza)
987         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
988         local declinee = jid_prep(payload.attr.to);
989         if not declinee then
990                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
991                 return true;
992         elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
993                 return true;
994         end
995         local decline = muc_util.filter_muc_x(st.clone(stanza));
996         decline.attr.from = self.jid;
997         decline.attr.to = declinee;
998         decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
999                         :tag("decline", {from = stanza.attr.from})
1000                                 :tag("reason"):text(payload:get_child_text("reason")):up()
1001                         :up()
1002                 :up();
1003         if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
1004                 declinee = decline.attr.to; -- re-fetch, in case event modified it
1005                 local occupant
1006                 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
1007                         occupant = self:get_occupant_by_nick(declinee);
1008                 end
1009                 if occupant then
1010                         self:route_to_occupant(occupant, decline);
1011                 else
1012                         self:route_stanza(decline);
1013                 end
1014         end
1015         return true;
1016 end
1017
1018 -- Add a plain message for clients which don't support declines
1019 module:hook("muc-decline", function(event)
1020         local room, stanza = event.room, event.stanza;
1021         if not stanza:get_child("body") then
1022                 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
1023                 local reason = decline:get_child_text("reason") or "";
1024                 stanza:tag("body")
1025                         :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
1026                 :up();
1027         end
1028 end);
1029
1030 function room_mt:handle_message_to_room(origin, stanza)
1031         local type = stanza.attr.type;
1032         if type == "groupchat" then
1033                 return self:handle_groupchat_to_room(origin, stanza)
1034         elseif type == "error" and is_kickable_error(stanza) then
1035                 return self:handle_kickable(origin, stanza)
1036         elseif type == nil then
1037                 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1038                 if x then
1039                         local payload = x.tags[1];
1040                         if payload == nil then --luacheck: ignore 542
1041                                 -- fallthrough
1042                         elseif payload.name == "invite" and payload.attr.to then
1043                                 return self:handle_mediated_invite(origin, stanza)
1044                         elseif payload.name == "decline" and payload.attr.to then
1045                                 return self:handle_mediated_decline(origin, stanza)
1046                         end
1047                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1048                         return true;
1049                 end
1050         end
1051 end
1052
1053 function room_mt:route_stanza(stanza) -- luacheck: ignore 212
1054         module:send(stanza);
1055 end
1056
1057 function room_mt:get_affiliation(jid)
1058         local node, host, resource = jid_split(jid);
1059         local bare = node and node.."@"..host or host;
1060         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1061         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1062         return result;
1063 end
1064
1065 -- Iterates over jid, affiliation pairs
1066 function room_mt:each_affiliation(with_affiliation)
1067         if not with_affiliation then
1068                 return pairs(self._affiliations);
1069         else
1070                 return function(_affiliations, jid)
1071                         local affiliation;
1072                         repeat -- Iterate until we get a match
1073                                 jid, affiliation = next(_affiliations, jid);
1074                         until jid == nil or affiliation == with_affiliation
1075                         return jid, affiliation;
1076                 end, self._affiliations, nil
1077         end
1078 end
1079
1080 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1081         if not actor then return nil, "modify", "not-acceptable"; end;
1082
1083         local node, host, resource = jid_split(jid);
1084         if not host then return nil, "modify", "not-acceptable"; end
1085         jid = jid_join(node, host); -- Bare
1086         local is_host_only = node == nil;
1087
1088         if valid_affiliations[affiliation or "none"] == nil then
1089                 return nil, "modify", "not-acceptable";
1090         end
1091         affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1092
1093         local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1094         local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1095
1096         if actor == true then
1097                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1098         else
1099                 local actor_affiliation = self:get_affiliation(actor);
1100                 if actor_affiliation == "owner" then
1101                         if jid_bare(actor) == jid then -- self change
1102                                 -- need at least one owner
1103                                 local is_last = true;
1104                                 for j in self:each_affiliation("owner") do
1105                                         if j ~= jid then is_last = false; break; end
1106                                 end
1107                                 if is_last then
1108                                         return nil, "cancel", "conflict";
1109                                 end
1110                         end
1111                         -- owners can do anything else
1112                 elseif affiliation == "owner" or affiliation == "admin"
1113                         or actor_affiliation ~= "admin"
1114                         or target_affiliation == "owner" or target_affiliation == "admin" then
1115                         -- Can't demote owners or other admins
1116                         return nil, "cancel", "not-allowed";
1117                 end
1118         end
1119
1120         -- Set in 'database'
1121         self._affiliations[jid] = affiliation;
1122
1123         -- Update roles
1124         local role = self:get_default_role(affiliation);
1125         local role_rank = valid_roles[role or "none"];
1126         local occupants_updated = {}; -- Filled with old roles
1127         for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
1128                 if occupant.bare_jid == jid or (
1129                         -- Outcast can be by host.
1130                         is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1131                 ) then
1132                         -- need to publcize in all cases; as affiliation in <item/> has changed.
1133                         occupants_updated[occupant] = occupant.role;
1134                         if occupant.role ~= role and (
1135                                 is_downgrade or
1136                                 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1137                         ) then
1138                                 occupant.role = role;
1139                                 self:save_occupant(occupant);
1140                         end
1141                 end
1142         end
1143
1144         -- Tell the room of the new occupant affiliations+roles
1145         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1146         if not role then -- getting kicked
1147                 if affiliation == "outcast" then
1148                         x:tag("status", {code="301"}):up(); -- banned
1149                 else
1150                         x:tag("status", {code="321"}):up(); -- affiliation change
1151                 end
1152         end
1153         local is_semi_anonymous = self:get_whois() == "moderators";
1154         for occupant, old_role in pairs(occupants_updated) do
1155                 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1156                 if occupant.role == nil then
1157                         module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1158                 elseif is_semi_anonymous and
1159                         (old_role == "moderator" and occupant.role ~= "moderator") or
1160                         (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1161                         -- Send everyone else's presences (as jid visibility has changed)
1162                         for real_jid in occupant:each_session() do
1163                                 self:send_occupant_list(real_jid, function(occupant_jid, occupant) --luacheck: ignore 212 433
1164                                         return occupant.bare_jid ~= jid;
1165                                 end);
1166                         end
1167                 end
1168         end
1169
1170         self:save();
1171
1172         module:fire_event("muc-set-affiliation", {
1173                 room = self;
1174                 actor = actor;
1175                 jid = jid;
1176                 affiliation = affiliation or "none";
1177                 reason = reason;
1178                 previous_affiliation = target_affiliation;
1179                 in_room = next(occupants_updated) ~= nil;
1180         });
1181
1182         return true;
1183 end
1184
1185 function room_mt:get_role(nick)
1186         local occupant = self:get_occupant_by_nick(nick);
1187         return occupant and occupant.role or nil;
1188 end
1189
1190 function room_mt:set_role(actor, occupant_jid, role, reason)
1191         if not actor then return nil, "modify", "not-acceptable"; end
1192
1193         local occupant = self:get_occupant_by_nick(occupant_jid);
1194         if not occupant then return nil, "modify", "item-not-found"; end
1195
1196         if valid_roles[role or "none"] == nil then
1197                 return nil, "modify", "not-acceptable";
1198         end
1199         role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1200
1201         if actor == true then
1202                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1203         else
1204                 -- Can't do anything to other owners or admins
1205                 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1206                 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1207                         return nil, "cancel", "not-allowed";
1208                 end
1209
1210                 -- If you are trying to give or take moderator role you need to be an owner or admin
1211                 if occupant.role == "moderator" or role == "moderator" then
1212                         local actor_affiliation = self:get_affiliation(actor);
1213                         if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1214                                 return nil, "cancel", "not-allowed";
1215                         end
1216                 end
1217
1218                 -- Need to be in the room and a moderator
1219                 local actor_occupant = self:get_occupant_by_real_jid(actor);
1220                 if not actor_occupant or actor_occupant.role ~= "moderator" then
1221                         return nil, "cancel", "not-allowed";
1222                 end
1223         end
1224
1225         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1226         if not role then
1227                 x:tag("status", {code = "307"}):up();
1228         end
1229         occupant.role = role;
1230         self:save_occupant(occupant);
1231         self:publicise_occupant_status(occupant, x, nil, actor, reason);
1232         if role == nil then
1233                 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1234         end
1235         return true;
1236 end
1237
1238 local whois = module:require "muc/whois";
1239 room_mt.get_whois = whois.get;
1240 room_mt.set_whois = whois.set;
1241
1242 local _M = {}; -- module "muc"
1243
1244 function _M.new_room(jid, config)
1245         return setmetatable({
1246                 jid = jid;
1247                 _jid_nick = {};
1248                 _occupants = {};
1249                 _data = config or {};
1250                 _affiliations = {};
1251         }, room_mt);
1252 end
1253
1254 function room_mt:freeze(live)
1255         local frozen = {
1256                 _jid = self.jid;
1257                 _data = self._data;
1258         };
1259         for user, affiliation in pairs(self._affiliations) do
1260                 frozen[user] = affiliation;
1261         end
1262         if live then
1263                 for nick, occupant in self:each_occupant() do
1264                         frozen[nick] = {
1265                                 bare_jid = occupant.bare_jid;
1266                                 role = occupant.role;
1267                                 jid = occupant.jid;
1268                         }
1269                         for jid, presence in occupant:each_session() do
1270                                 frozen[jid] = st.preserialize(presence);
1271                         end
1272                 end
1273         end
1274         return frozen;
1275 end
1276
1277 function _M.restore_room(frozen)
1278         -- COMPAT
1279         if frozen.jid and frozen._affiliations then
1280                 local room = _M.new_room(frozen.jid, frozen._data);
1281                 room._affiliations = frozen._affiliations;
1282                 return room;
1283         end
1284
1285         local room_jid = frozen._jid;
1286         local room = _M.new_room(room_jid, frozen._data);
1287
1288         local occupants = {};
1289         local occupant_sessions = {};
1290         local room_name, room_host = jid_split(room_jid);
1291         for jid, data in pairs(frozen) do
1292                 local node, host, resource = jid_split(jid);
1293                 if node or host:sub(1,1) ~= "_" then
1294                         if not resource and type(data) == "string" then
1295                                 -- bare jid: affiliation
1296                                 room._affiliations[jid] = data;
1297                         elseif host == room_host and node == room_name and resource then
1298                                 -- full room jid: bare real jid and role
1299                                 local bare_jid = data.bare_jid;
1300                                 local   occupant = occupant_lib.new(bare_jid, jid);
1301                                 occupant.jid = data.jid;
1302                                 occupant.role = data.role;
1303                                 occupants[bare_jid] = occupant;
1304                                 local sessions = occupant_sessions[bare_jid];
1305                                 if sessions then
1306                                         for full_jid, presence in pairs(sessions) do
1307                                                 occupant:set_session(full_jid, presence);
1308                                         end
1309                                 end
1310                                 occupant_sessions[bare_jid] = nil;
1311                         else
1312                                 -- full user jid: presence
1313                                 local presence = st.deserialize(data);
1314                                 local bare_jid = jid_bare(jid);
1315                                 local occupant = occupants[bare_jid];
1316                                 local sessions = occupant_sessions[bare_jid];
1317                                 if occupant then
1318                                         occupant:set_session(jid, presence);
1319                                 elseif sessions then
1320                                         sessions[jid] = presence;
1321                                 else
1322                                         occupant_sessions[bare_jid] = {
1323                                                 [jid] = presence;
1324                                         };
1325                                 end
1326                         end
1327                 end
1328         end
1329
1330         for _, occupant in pairs(occupants) do
1331                 room:save_occupant(occupant);
1332         end
1333
1334         return room;
1335 end
1336
1337 _M.room_mt = room_mt;
1338
1339 return _M;