MUC: Split out handling of normal (un)available presence into its own method
[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_normal_presence(origin, stanza)
388         local type = stanza.attr.type;
389         local real_jid = stanza.attr.from;
390         local bare_jid = jid_bare(real_jid);
391         local orig_occupant, dest_occupant;
392         local is_new_room = next(self._affiliations) == nil;
393         if is_new_room then
394                 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
395                 if module:fire_event("muc-room-pre-create", {
396                                 room = self;
397                                 origin = origin;
398                                 stanza = stanza;
399                         }) then return true; end
400         else
401                 orig_occupant = self:get_occupant_by_real_jid(real_jid);
402                 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
403         end
404         local is_first_dest_session;
405         if type == "unavailable" then -- luacheck: ignore 542
406                 -- FIXME Why the empty if branch?
407                 -- dest_occupant = nil
408         elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
409                 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
410                 dest_occupant = orig_occupant;
411         else
412                 local dest_jid = stanza.attr.to;
413                 dest_occupant = self:get_occupant_by_nick(dest_jid);
414                 if dest_occupant == nil then
415                         log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
416                         is_first_dest_session = true;
417                         dest_occupant = self:new_occupant(bare_jid, dest_jid);
418                 else
419                         is_first_dest_session = false;
420                 end
421         end
422         local is_last_orig_session;
423         if orig_occupant ~= nil then
424                 -- Is there are least 2 sessions?
425                 local iter, ob, last = orig_occupant:each_session();
426                 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
427         end
428
429         -- TODO Handle these cases sensibly
430         local muc_x = stanza:get_child("x", "http://jabber.org/protocol/muc");
431         if orig_occupant == nil and not muc_x then
432                 module:log("debug", "Join without <x>, possibly desynced");
433         elseif orig_occupant ~= nil and muc_x then
434                 module:log("debug", "Presence update with <x>, possibly desynced");
435         end
436
437         local event, event_name = {
438                 room = self;
439                 origin = origin;
440                 stanza = stanza;
441                 is_first_session = is_first_dest_session;
442                 is_last_session = is_last_orig_session;
443         };
444         if orig_occupant == nil then
445                 event_name = "muc-occupant-pre-join";
446                 event.is_new_room = is_new_room;
447                 event.occupant = dest_occupant;
448         elseif dest_occupant == nil then
449                 event_name = "muc-occupant-pre-leave";
450                 event.occupant = orig_occupant;
451         else
452                 event_name = "muc-occupant-pre-change";
453                 event.orig_occupant = orig_occupant;
454                 event.dest_occupant = dest_occupant;
455         end
456         if module:fire_event(event_name, event) then return true; end
457
458         -- Check for nick conflicts
459         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
460                 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
461                 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
462                 reply.tags[1].attr.code = "409";
463                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
464                 return true;
465         end
466
467         -- Send presence stanza about original occupant
468         if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
469                 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
470                 local dest_nick;
471                 if dest_occupant == nil then -- Session is leaving
472                         log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
473                         if is_last_orig_session then
474                                 orig_occupant.role = nil;
475                         end
476                         orig_occupant:set_session(real_jid, stanza);
477                 else
478                         log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
479                         local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
480                         orig_occupant:set_session(real_jid, generated_unavail);
481                         dest_nick = select(3, jid_split(dest_occupant.nick));
482                         if not is_first_dest_session then -- User is swapping into another pre-existing session
483                                 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
484                                 -- Show the other session leaving
485                                 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
486                                         :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
487                                 add_item(x, self:get_affiliation(bare_jid), "none");
488                                 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
489                                         :add_child(x);
490                                 self:route_stanza(pr);
491                         end
492                         if is_first_dest_session and is_last_orig_session then -- Normal nick change
493                                 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
494                                 orig_x:tag("status", {code = "303";}):up();
495                         else -- The session itself always needs to see a nick change
496                                 -- don't want to get our old nick's available presence,
497                                 -- so remove our session from there, and manually generate an unavailable
498                                 orig_occupant:remove_session(real_jid);
499                                 log("debug", "generating nick change for %s", real_jid);
500                                 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
501                                 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
502                                 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
503                                 x:tag("status", {code = "303";}):up();
504                                 x:tag("status", {code = "110";}):up();
505                                 self:route_stanza(generated_unavail:add_child(x));
506                                 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
507                         end
508                 end
509                 self:save_occupant(orig_occupant);
510                 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
511
512                 if is_last_orig_session then
513                         module:fire_event("muc-occupant-left", {
514                                 room = self;
515                                 nick = orig_occupant.nick;
516                                 occupant = orig_occupant;
517                                 origin = origin;
518                                 stanza = stanza;
519                         });
520                 end
521         end
522
523         if dest_occupant ~= nil then
524                 dest_occupant:set_session(real_jid, stanza);
525                 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
526                 if is_new_room then
527                         dest_x:tag("status", {code = "201"}):up();
528                 end
529                 if orig_occupant == nil and self:get_whois() == "anyone" then
530                         dest_x:tag("status", {code = "100"}):up();
531                 end
532                 self:save_occupant(dest_occupant);
533
534                 if orig_occupant == nil then
535                         -- Send occupant list to newly joined user
536                         self:send_occupant_list(real_jid, function(nick, occupant) -- luacheck: ignore 212
537                                 -- Don't include self
538                                 return occupant:get_presence(real_jid) == nil;
539                         end)
540                 end
541                 self:publicise_occupant_status(dest_occupant, dest_x);
542
543                 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
544                         log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
545                         -- Show the original nick joining again
546                         local pr = st.clone(orig_occupant:get_presence());
547                         pr.attr.to = real_jid;
548                         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
549                         self:build_item_list(orig_occupant, x, false);
550                         -- TODO: new status code to inform client this was the multi-session it left?
551                         pr:add_child(x);
552                         self:route_stanza(pr);
553                 end
554
555                 if orig_occupant == nil then
556                         if is_first_dest_session then
557                                 module:fire_event("muc-occupant-joined", {
558                                         room = self;
559                                         nick = dest_occupant.nick;
560                                         occupant = dest_occupant;
561                                         stanza = stanza;
562                                         origin = origin;
563                                 });
564                         end
565                         module:fire_event("muc-occupant-session-new", {
566                                 room = self;
567                                 nick = dest_occupant.nick;
568                                 occupant = dest_occupant;
569                                 stanza = stanza;
570                                 origin = origin;
571                                 jid = real_jid;
572                         });
573                 end
574         end
575         return true;
576 end
577
578 function room_mt:handle_presence_to_occupant(origin, stanza)
579         local type = stanza.attr.type;
580         if type == "error" then -- error, kick em out!
581                 return self:handle_kickable(origin, stanza)
582         elseif type == nil or type == "unavailable" then
583                 return self:handle_normal_presence(origin, stanza);
584         elseif type ~= 'result' then -- bad type
585                 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
586                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
587                 end
588         end
589         return true;
590 end
591
592 function room_mt:handle_iq_to_occupant(origin, stanza)
593         local from, to = stanza.attr.from, stanza.attr.to;
594         local type = stanza.attr.type;
595         local id = stanza.attr.id;
596         local occupant = self:get_occupant_by_nick(to);
597         if (type == "error" or type == "result") then
598                 do -- deconstruct_stanza_id
599                         if not occupant then return nil; end
600                         local from_jid, orig_id, to_jid_hash = (base64.decode(id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
601                         if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
602                         local from_occupant_jid = self:get_occupant_jid(from_jid);
603                         if from_occupant_jid == nil then return nil; end
604                         local session_jid
605                         for to_jid in occupant:each_session() do
606                                 if md5(to_jid) == to_jid_hash then
607                                         session_jid = to_jid;
608                                         break;
609                                 end
610                         end
611                         if session_jid == nil then return nil; end
612                         stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, orig_id;
613                 end
614                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
615                 self:route_stanza(stanza);
616                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
617                 return true;
618         else -- Type is "get" or "set"
619                 local current_nick = self:get_occupant_jid(from);
620                 if not current_nick then
621                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
622                         return true;
623                 end
624                 if not occupant then -- recipient not in room
625                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
626                         return true;
627                 end
628                 do -- construct_stanza_id
629                         stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
630                 end
631                 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
632                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
633                 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
634                         stanza.attr.to = jid_bare(stanza.attr.to);
635                 end
636                 self:route_stanza(stanza);
637                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
638                 return true;
639         end
640 end
641
642 function room_mt:handle_message_to_occupant(origin, stanza)
643         local from, to = stanza.attr.from, stanza.attr.to;
644         local current_nick = self:get_occupant_jid(from);
645         local type = stanza.attr.type;
646         if not current_nick then -- not in room
647                 if type ~= "error" then
648                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
649                 end
650                 return true;
651         end
652         if type == "groupchat" then -- groupchat messages not allowed in PM
653                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
654                 return true;
655         elseif type == "error" and is_kickable_error(stanza) then
656                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
657                 return self:handle_kickable(origin, stanza); -- send unavailable
658         end
659
660         local o_data = self:get_occupant_by_nick(to);
661         if not o_data then
662                 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
663                 return true;
664         end
665         log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
666         stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
667         stanza.attr.from = current_nick;
668         self:route_to_occupant(o_data, stanza)
669         -- TODO: Remove x tag?
670         stanza.attr.from = from;
671         return true;
672 end
673
674 function room_mt:send_form(origin, stanza)
675         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
676                 :add_child(self:get_form_layout(stanza.attr.from):form())
677         );
678 end
679
680 function room_mt:get_form_layout(actor)
681         local form = dataform.new({
682                 title = "Configuration for "..self.jid,
683                 instructions = "Complete and submit this form to configure the room.",
684                 {
685                         name = 'FORM_TYPE',
686                         type = 'hidden',
687                         value = 'http://jabber.org/protocol/muc#roomconfig'
688                 }
689         });
690         return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
691 end
692
693 function room_mt:process_form(origin, stanza)
694         local form = stanza.tags[1]:get_child("x", "jabber:x:data");
695         if form.attr.type == "cancel" then
696                 origin.send(st.reply(stanza));
697         elseif form.attr.type == "submit" then
698                 local fields, errors, present;
699                 if form.tags[1] == nil then -- Instant room
700                         fields, present = {}, {};
701                 else
702                         fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
703                         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
704                                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
705                                 return true;
706                         end
707                 end
708
709                 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
710                 function event.update_option(name, field, allowed)
711                         local new = fields[field];
712                         if new == nil then return; end
713                         if allowed and not allowed[new] then return; end
714                         if new == self["get_"..name](self) then return; end
715                         event.status_codes["104"] = true;
716                         self["set_"..name](self, new);
717                         return true;
718                 end
719                 module:fire_event("muc-config-submitted", event);
720                 for submitted_field in pairs(present) do
721                         event.field, event.value = submitted_field, fields[submitted_field];
722                         module:fire_event("muc-config-submitted/"..submitted_field, event);
723                 end
724                 event.field, event.value = nil, nil;
725
726                 self:save();
727                 origin.send(st.reply(stanza));
728
729                 if next(event.status_codes) then
730                         local msg = st.message({type='groupchat', from=self.jid})
731                                 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
732                         for code in pairs(event.status_codes) do
733                                 msg:tag("status", {code = code;}):up();
734                         end
735                         msg:up();
736                         self:broadcast_message(msg);
737                 end
738         else
739                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
740         end
741         return true;
742 end
743
744 -- Removes everyone from the room
745 function room_mt:clear(x)
746         x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
747         local occupants_updated = {};
748         for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
749                 occupant.role = nil;
750                 self:save_occupant(occupant);
751                 occupants_updated[occupant] = true;
752         end
753         for occupant in pairs(occupants_updated) do
754                 self:publicise_occupant_status(occupant, x);
755                 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
756         end
757 end
758
759 function room_mt:destroy(newjid, reason, password)
760         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
761                 :tag("item", { affiliation='none', role='none' }):up()
762                 :tag("destroy", {jid=newjid});
763         if reason then x:tag("reason"):text(reason):up(); end
764         if password then x:tag("password"):text(password):up(); end
765         x:up();
766         self:clear(x);
767         module:fire_event("muc-room-destroyed", { room = self });
768 end
769
770 function room_mt:handle_disco_info_get_query(origin, stanza)
771         origin.send(self:get_disco_info(stanza));
772         return true;
773 end
774
775 function room_mt:handle_disco_items_get_query(origin, stanza)
776         origin.send(self:get_disco_items(stanza));
777         return true;
778 end
779
780 function room_mt:handle_admin_query_set_command(origin, stanza)
781         local item = stanza.tags[1].tags[1];
782         if not item then
783                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
784         end
785         if item.attr.jid then -- Validate provided JID
786                 item.attr.jid = jid_prep(item.attr.jid);
787                 if not item.attr.jid then
788                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
789                         return true;
790                 end
791         end
792         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
793                 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
794                 if occupant then item.attr.jid = occupant.jid; end
795         elseif not item.attr.nick and item.attr.jid then
796                 local nick = self:get_occupant_jid(item.attr.jid);
797                 if nick then item.attr.nick = select(3, jid_split(nick)); end
798         end
799         local actor = stanza.attr.from;
800         local reason = item:get_child_text("reason");
801         local success, errtype, err
802         if item.attr.affiliation and item.attr.jid and not item.attr.role then
803                 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
804         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
805                 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
806         else
807                 success, errtype, err = nil, "cancel", "bad-request";
808         end
809         self:save();
810         if not success then
811                 origin.send(st.error_reply(stanza, errtype, err));
812         else
813                 origin.send(st.reply(stanza));
814         end
815         return true;
816 end
817
818 function room_mt:handle_admin_query_get_command(origin, stanza)
819         local actor = stanza.attr.from;
820         local affiliation = self:get_affiliation(actor);
821         local item = stanza.tags[1].tags[1];
822         local _aff = item.attr.affiliation;
823         local _aff_rank = valid_affiliations[_aff or "none"];
824         local _rol = item.attr.role;
825         if _aff and _aff_rank and not _rol then
826                 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
827                 -- e.g. an admin can't ask for a list of owners
828                 local affiliation_rank = valid_affiliations[affiliation or "none"];
829                 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
830                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
831                         for jid in self:each_affiliation(_aff or "none") do
832                                 reply:tag("item", {affiliation = _aff, jid = jid}):up();
833                         end
834                         origin.send(reply:up());
835                         return true;
836                 else
837                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
838                         return true;
839                 end
840         elseif _rol and valid_roles[_rol or "none"] and not _aff then
841                 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
842                 if valid_roles[role or "none"] >= valid_roles.moderator then
843                         if _rol == "none" then _rol = nil; end
844                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
845                         -- TODO: whois check here? (though fully anonymous rooms are not supported)
846                         for occupant_jid, occupant in self:each_occupant() do
847                                 if occupant.role == _rol then
848                                         local nick = select(3,jid_split(occupant_jid));
849                                         self:build_item_list(occupant, reply, false, nick);
850                                 end
851                         end
852                         origin.send(reply:up());
853                         return true;
854                 else
855                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
856                         return true;
857                 end
858         else
859                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
860                 return true;
861         end
862 end
863
864 function room_mt:handle_owner_query_get_to_room(origin, stanza)
865         if self:get_affiliation(stanza.attr.from) ~= "owner" then
866                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
867                 return true;
868         end
869
870         self:send_form(origin, stanza);
871         return true;
872 end
873 function room_mt:handle_owner_query_set_to_room(origin, stanza)
874         if self:get_affiliation(stanza.attr.from) ~= "owner" then
875                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
876                 return true;
877         end
878
879         local child = stanza.tags[1].tags[1];
880         if not child then
881                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
882                 return true;
883         elseif child.name == "destroy" then
884                 local newjid = child.attr.jid;
885                 local reason = child:get_child_text("reason");
886                 local password = child:get_child_text("password");
887                 self:destroy(newjid, reason, password);
888                 origin.send(st.reply(stanza));
889                 return true;
890         elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
891                 return self:process_form(origin, stanza);
892         else
893                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
894                 return true;
895         end
896 end
897
898 function room_mt:handle_groupchat_to_room(origin, stanza)
899         local from = stanza.attr.from;
900         local occupant = self:get_occupant_by_real_jid(from);
901         if module:fire_event("muc-occupant-groupchat", {
902                 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
903         }) then return true; end
904         stanza.attr.from = occupant.nick;
905         self:broadcast_message(stanza);
906         stanza.attr.from = from;
907         return true;
908 end
909
910 -- Role check
911 module:hook("muc-occupant-groupchat", function(event)
912         local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
913         if role_rank <= valid_roles.none then
914                 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
915                 return true;
916         elseif role_rank <= valid_roles.visitor then
917                 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
918                 return true;
919         end
920 end, 50);
921
922 -- hack - some buggy clients send presence updates to the room rather than their nick
923 function room_mt:handle_presence_to_room(origin, stanza)
924         local current_nick = self:get_occupant_jid(stanza.attr.from);
925         local handled
926         if current_nick then
927                 local to = stanza.attr.to;
928                 stanza.attr.to = current_nick;
929                 handled = self:handle_presence_to_occupant(origin, stanza);
930                 stanza.attr.to = to;
931         end
932         return handled;
933 end
934
935 -- Need visitor role or higher to invite
936 module:hook("muc-pre-invite", function(event)
937         local room, stanza = event.room, event.stanza;
938         local _from = stanza.attr.from;
939         local inviter = room:get_occupant_by_real_jid(_from);
940         local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
941         if valid_roles[role or "none"] <= valid_roles.visitor then
942                 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
943                 return true;
944         end
945 end);
946
947 function room_mt:handle_mediated_invite(origin, stanza)
948         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
949         local invitee = jid_prep(payload.attr.to);
950         if not invitee then
951                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
952                 return true;
953         elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
954                 return true;
955         end
956         local invite = muc_util.filter_muc_x(st.clone(stanza));
957         invite.attr.from = self.jid;
958         invite.attr.to = invitee;
959         invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
960                         :tag('invite', {from = stanza.attr.from;})
961                                 :tag('reason'):text(payload:get_child_text("reason")):up()
962                         :up()
963                 :up();
964         if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
965                 self:route_stanza(invite);
966         end
967         return true;
968 end
969
970 -- COMPAT: Some older clients expect this
971 module:hook("muc-invite", function(event)
972         local room, stanza = event.room, event.stanza;
973         local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
974         local reason = invite:get_child_text("reason");
975         stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
976                 :text(reason or "")
977         :up();
978 end);
979
980 -- Add a plain message for clients which don't support invites
981 module:hook("muc-invite", function(event)
982         local room, stanza = event.room, event.stanza;
983         if not stanza:get_child("body") then
984                 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
985                 local reason = invite:get_child_text("reason") or "";
986                 stanza:tag("body")
987                         :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
988                 :up();
989         end
990 end);
991
992 function room_mt:handle_mediated_decline(origin, stanza)
993         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
994         local declinee = jid_prep(payload.attr.to);
995         if not declinee then
996                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
997                 return true;
998         elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
999                 return true;
1000         end
1001         local decline = muc_util.filter_muc_x(st.clone(stanza));
1002         decline.attr.from = self.jid;
1003         decline.attr.to = declinee;
1004         decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1005                         :tag("decline", {from = stanza.attr.from})
1006                                 :tag("reason"):text(payload:get_child_text("reason")):up()
1007                         :up()
1008                 :up();
1009         if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
1010                 declinee = decline.attr.to; -- re-fetch, in case event modified it
1011                 local occupant
1012                 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
1013                         occupant = self:get_occupant_by_nick(declinee);
1014                 end
1015                 if occupant then
1016                         self:route_to_occupant(occupant, decline);
1017                 else
1018                         self:route_stanza(decline);
1019                 end
1020         end
1021         return true;
1022 end
1023
1024 -- Add a plain message for clients which don't support declines
1025 module:hook("muc-decline", function(event)
1026         local room, stanza = event.room, event.stanza;
1027         if not stanza:get_child("body") then
1028                 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
1029                 local reason = decline:get_child_text("reason") or "";
1030                 stanza:tag("body")
1031                         :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
1032                 :up();
1033         end
1034 end);
1035
1036 function room_mt:handle_message_to_room(origin, stanza)
1037         local type = stanza.attr.type;
1038         if type == "groupchat" then
1039                 return self:handle_groupchat_to_room(origin, stanza)
1040         elseif type == "error" and is_kickable_error(stanza) then
1041                 return self:handle_kickable(origin, stanza)
1042         elseif type == nil then
1043                 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1044                 if x then
1045                         local payload = x.tags[1];
1046                         if payload == nil then --luacheck: ignore 542
1047                                 -- fallthrough
1048                         elseif payload.name == "invite" and payload.attr.to then
1049                                 return self:handle_mediated_invite(origin, stanza)
1050                         elseif payload.name == "decline" and payload.attr.to then
1051                                 return self:handle_mediated_decline(origin, stanza)
1052                         end
1053                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1054                         return true;
1055                 end
1056         end
1057 end
1058
1059 function room_mt:route_stanza(stanza) -- luacheck: ignore 212
1060         module:send(stanza);
1061 end
1062
1063 function room_mt:get_affiliation(jid)
1064         local node, host, resource = jid_split(jid);
1065         local bare = node and node.."@"..host or host;
1066         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1067         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1068         return result;
1069 end
1070
1071 -- Iterates over jid, affiliation pairs
1072 function room_mt:each_affiliation(with_affiliation)
1073         if not with_affiliation then
1074                 return pairs(self._affiliations);
1075         else
1076                 return function(_affiliations, jid)
1077                         local affiliation;
1078                         repeat -- Iterate until we get a match
1079                                 jid, affiliation = next(_affiliations, jid);
1080                         until jid == nil or affiliation == with_affiliation
1081                         return jid, affiliation;
1082                 end, self._affiliations, nil
1083         end
1084 end
1085
1086 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1087         if not actor then return nil, "modify", "not-acceptable"; end;
1088
1089         local node, host, resource = jid_split(jid);
1090         if not host then return nil, "modify", "not-acceptable"; end
1091         jid = jid_join(node, host); -- Bare
1092         local is_host_only = node == nil;
1093
1094         if valid_affiliations[affiliation or "none"] == nil then
1095                 return nil, "modify", "not-acceptable";
1096         end
1097         affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1098
1099         local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1100         local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1101
1102         if actor == true then
1103                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1104         else
1105                 local actor_affiliation = self:get_affiliation(actor);
1106                 if actor_affiliation == "owner" then
1107                         if jid_bare(actor) == jid then -- self change
1108                                 -- need at least one owner
1109                                 local is_last = true;
1110                                 for j in self:each_affiliation("owner") do
1111                                         if j ~= jid then is_last = false; break; end
1112                                 end
1113                                 if is_last then
1114                                         return nil, "cancel", "conflict";
1115                                 end
1116                         end
1117                         -- owners can do anything else
1118                 elseif affiliation == "owner" or affiliation == "admin"
1119                         or actor_affiliation ~= "admin"
1120                         or target_affiliation == "owner" or target_affiliation == "admin" then
1121                         -- Can't demote owners or other admins
1122                         return nil, "cancel", "not-allowed";
1123                 end
1124         end
1125
1126         -- Set in 'database'
1127         self._affiliations[jid] = affiliation;
1128
1129         -- Update roles
1130         local role = self:get_default_role(affiliation);
1131         local role_rank = valid_roles[role or "none"];
1132         local occupants_updated = {}; -- Filled with old roles
1133         for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
1134                 if occupant.bare_jid == jid or (
1135                         -- Outcast can be by host.
1136                         is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1137                 ) then
1138                         -- need to publcize in all cases; as affiliation in <item/> has changed.
1139                         occupants_updated[occupant] = occupant.role;
1140                         if occupant.role ~= role and (
1141                                 is_downgrade or
1142                                 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1143                         ) then
1144                                 occupant.role = role;
1145                                 self:save_occupant(occupant);
1146                         end
1147                 end
1148         end
1149
1150         -- Tell the room of the new occupant affiliations+roles
1151         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1152         if not role then -- getting kicked
1153                 if affiliation == "outcast" then
1154                         x:tag("status", {code="301"}):up(); -- banned
1155                 else
1156                         x:tag("status", {code="321"}):up(); -- affiliation change
1157                 end
1158         end
1159         local is_semi_anonymous = self:get_whois() == "moderators";
1160         for occupant, old_role in pairs(occupants_updated) do
1161                 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1162                 if occupant.role == nil then
1163                         module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1164                 elseif is_semi_anonymous and
1165                         (old_role == "moderator" and occupant.role ~= "moderator") or
1166                         (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1167                         -- Send everyone else's presences (as jid visibility has changed)
1168                         for real_jid in occupant:each_session() do
1169                                 self:send_occupant_list(real_jid, function(occupant_jid, occupant) --luacheck: ignore 212 433
1170                                         return occupant.bare_jid ~= jid;
1171                                 end);
1172                         end
1173                 end
1174         end
1175
1176         self:save();
1177
1178         module:fire_event("muc-set-affiliation", {
1179                 room = self;
1180                 actor = actor;
1181                 jid = jid;
1182                 affiliation = affiliation or "none";
1183                 reason = reason;
1184                 previous_affiliation = target_affiliation;
1185                 in_room = next(occupants_updated) ~= nil;
1186         });
1187
1188         return true;
1189 end
1190
1191 function room_mt:get_role(nick)
1192         local occupant = self:get_occupant_by_nick(nick);
1193         return occupant and occupant.role or nil;
1194 end
1195
1196 function room_mt:set_role(actor, occupant_jid, role, reason)
1197         if not actor then return nil, "modify", "not-acceptable"; end
1198
1199         local occupant = self:get_occupant_by_nick(occupant_jid);
1200         if not occupant then return nil, "modify", "item-not-found"; end
1201
1202         if valid_roles[role or "none"] == nil then
1203                 return nil, "modify", "not-acceptable";
1204         end
1205         role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1206
1207         if actor == true then
1208                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1209         else
1210                 -- Can't do anything to other owners or admins
1211                 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1212                 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1213                         return nil, "cancel", "not-allowed";
1214                 end
1215
1216                 -- If you are trying to give or take moderator role you need to be an owner or admin
1217                 if occupant.role == "moderator" or role == "moderator" then
1218                         local actor_affiliation = self:get_affiliation(actor);
1219                         if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1220                                 return nil, "cancel", "not-allowed";
1221                         end
1222                 end
1223
1224                 -- Need to be in the room and a moderator
1225                 local actor_occupant = self:get_occupant_by_real_jid(actor);
1226                 if not actor_occupant or actor_occupant.role ~= "moderator" then
1227                         return nil, "cancel", "not-allowed";
1228                 end
1229         end
1230
1231         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1232         if not role then
1233                 x:tag("status", {code = "307"}):up();
1234         end
1235         occupant.role = role;
1236         self:save_occupant(occupant);
1237         self:publicise_occupant_status(occupant, x, nil, actor, reason);
1238         if role == nil then
1239                 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1240         end
1241         return true;
1242 end
1243
1244 local whois = module:require "muc/whois";
1245 room_mt.get_whois = whois.get;
1246 room_mt.set_whois = whois.set;
1247
1248 local _M = {}; -- module "muc"
1249
1250 function _M.new_room(jid, config)
1251         return setmetatable({
1252                 jid = jid;
1253                 _jid_nick = {};
1254                 _occupants = {};
1255                 _data = config or {};
1256                 _affiliations = {};
1257         }, room_mt);
1258 end
1259
1260 function room_mt:freeze(live)
1261         local frozen = {
1262                 _jid = self.jid;
1263                 _data = self._data;
1264         };
1265         for user, affiliation in pairs(self._affiliations) do
1266                 frozen[user] = affiliation;
1267         end
1268         if live then
1269                 for nick, occupant in self:each_occupant() do
1270                         frozen[nick] = {
1271                                 bare_jid = occupant.bare_jid;
1272                                 role = occupant.role;
1273                                 jid = occupant.jid;
1274                         }
1275                         for jid, presence in occupant:each_session() do
1276                                 frozen[jid] = st.preserialize(presence);
1277                         end
1278                 end
1279         end
1280         return frozen;
1281 end
1282
1283 function _M.restore_room(frozen)
1284         -- COMPAT
1285         if frozen.jid and frozen._affiliations then
1286                 local room = _M.new_room(frozen.jid, frozen._data);
1287                 room._affiliations = frozen._affiliations;
1288                 return room;
1289         end
1290
1291         local room_jid = frozen._jid;
1292         local room = _M.new_room(room_jid, frozen._data);
1293
1294         local occupants = {};
1295         local occupant_sessions = {};
1296         local room_name, room_host = jid_split(room_jid);
1297         for jid, data in pairs(frozen) do
1298                 local node, host, resource = jid_split(jid);
1299                 if node or host:sub(1,1) ~= "_" then
1300                         if not resource and type(data) == "string" then
1301                                 -- bare jid: affiliation
1302                                 room._affiliations[jid] = data;
1303                         elseif host == room_host and node == room_name and resource then
1304                                 -- full room jid: bare real jid and role
1305                                 local bare_jid = data.bare_jid;
1306                                 local   occupant = occupant_lib.new(bare_jid, jid);
1307                                 occupant.jid = data.jid;
1308                                 occupant.role = data.role;
1309                                 occupants[bare_jid] = occupant;
1310                                 local sessions = occupant_sessions[bare_jid];
1311                                 if sessions then
1312                                         for full_jid, presence in pairs(sessions) do
1313                                                 occupant:set_session(full_jid, presence);
1314                                         end
1315                                 end
1316                                 occupant_sessions[bare_jid] = nil;
1317                         else
1318                                 -- full user jid: presence
1319                                 local presence = st.deserialize(data);
1320                                 local bare_jid = jid_bare(jid);
1321                                 local occupant = occupants[bare_jid];
1322                                 local sessions = occupant_sessions[bare_jid];
1323                                 if occupant then
1324                                         occupant:set_session(jid, presence);
1325                                 elseif sessions then
1326                                         sessions[jid] = presence;
1327                                 else
1328                                         occupant_sessions[bare_jid] = {
1329                                                 [jid] = presence;
1330                                         };
1331                                 end
1332                         end
1333                 end
1334         end
1335
1336         for _, occupant in pairs(occupants) do
1337                 room:save_occupant(occupant);
1338         end
1339
1340         return room;
1341 end
1342
1343 _M.room_mt = room_mt;
1344
1345 return _M;