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