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