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