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