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 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", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
495                         end
496                 end
497
498                 if dest_occupant ~= nil then
499                         dest_occupant:set_session(real_jid, stanza);
500                         local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
501                         if is_new_room then
502                                 dest_x:tag("status", {code = "201"}):up();
503                         end
504                         if orig_occupant == nil and self:get_whois() == "anyone" then
505                                 dest_x:tag("status", {code = "100"}):up();
506                         end
507                         self:save_occupant(dest_occupant);
508
509                         if orig_occupant == nil then
510                                 -- Send occupant list to newly joined user
511                                 self:send_occupant_list(real_jid, function(nick, occupant) -- luacheck: ignore 212
512                                         -- Don't include self
513                                         return occupant:get_presence(real_jid) == nil;
514                                 end)
515                         end
516                         self:publicise_occupant_status(dest_occupant, dest_x);
517
518                         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
519                                 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
520                                 -- Show the original nick joining again
521                                 local pr = st.clone(orig_occupant:get_presence());
522                                 pr.attr.to = real_jid;
523                                 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
524                                 self:build_item_list(orig_occupant, x, false);
525                                 -- TODO: new status code to inform client this was the multi-session it left?
526                                 pr:add_child(x);
527                                 self:route_stanza(pr);
528                         end
529
530                         if orig_occupant == nil then
531                                 if is_first_dest_session then
532                                         module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
533                                 end
534                                 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
535                         end
536                 end
537         elseif type ~= 'result' then -- bad type
538                 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
539                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
540                 end
541         end
542         return true;
543 end
544
545 function room_mt:handle_iq_to_occupant(origin, stanza)
546         local from, to = stanza.attr.from, stanza.attr.to;
547         local type = stanza.attr.type;
548         local id = stanza.attr.id;
549         local occupant = self:get_occupant_by_nick(to);
550         if (type == "error" or type == "result") then
551                 do -- deconstruct_stanza_id
552                         if not occupant then return nil; end
553                         local from_jid, orig_id, to_jid_hash = (base64.decode(id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
554                         if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
555                         local from_occupant_jid = self:get_occupant_jid(from_jid);
556                         if from_occupant_jid == nil then return nil; end
557                         local session_jid
558                         for to_jid in occupant:each_session() do
559                                 if md5(to_jid) == to_jid_hash then
560                                         session_jid = to_jid;
561                                         break;
562                                 end
563                         end
564                         if session_jid == nil then return nil; end
565                         stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, orig_id;
566                 end
567                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
568                 self:route_stanza(stanza);
569                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
570                 return true;
571         else -- Type is "get" or "set"
572                 local current_nick = self:get_occupant_jid(from);
573                 if not current_nick then
574                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
575                         return true;
576                 end
577                 if not occupant then -- recipient not in room
578                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
579                         return true;
580                 end
581                 do -- construct_stanza_id
582                         stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
583                 end
584                 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
585                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
586                 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
587                         stanza.attr.to = jid_bare(stanza.attr.to);
588                 end
589                 self:route_stanza(stanza);
590                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
591                 return true;
592         end
593 end
594
595 function room_mt:handle_message_to_occupant(origin, stanza)
596         local from, to = stanza.attr.from, stanza.attr.to;
597         local current_nick = self:get_occupant_jid(from);
598         local type = stanza.attr.type;
599         if not current_nick then -- not in room
600                 if type ~= "error" then
601                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
602                 end
603                 return true;
604         end
605         if type == "groupchat" then -- groupchat messages not allowed in PM
606                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
607                 return true;
608         elseif type == "error" and is_kickable_error(stanza) then
609                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
610                 return self:handle_kickable(origin, stanza); -- send unavailable
611         end
612
613         local o_data = self:get_occupant_by_nick(to);
614         if not o_data then
615                 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
616                 return true;
617         end
618         log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
619         stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
620         stanza.attr.from = current_nick;
621         self:route_to_occupant(o_data, stanza)
622         -- TODO: Remove x tag?
623         stanza.attr.from = from;
624         return true;
625 end
626
627 function room_mt:send_form(origin, stanza)
628         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
629                 :add_child(self:get_form_layout(stanza.attr.from):form())
630         );
631 end
632
633 function room_mt:get_form_layout(actor)
634         local form = dataform.new({
635                 title = "Configuration for "..self.jid,
636                 instructions = "Complete and submit this form to configure the room.",
637                 {
638                         name = 'FORM_TYPE',
639                         type = 'hidden',
640                         value = 'http://jabber.org/protocol/muc#roomconfig'
641                 }
642         });
643         return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
644 end
645
646 function room_mt:process_form(origin, stanza)
647         local form = stanza.tags[1]:get_child("x", "jabber:x:data");
648         if form.attr.type == "cancel" then
649                 origin.send(st.reply(stanza));
650         elseif form.attr.type == "submit" then
651                 local fields, errors, present;
652                 if form.tags[1] == nil then -- Instant room
653                         fields, present = {}, {};
654                 else
655                         fields, errors, present = self:get_form_layout(stanza.attr.from):data(form);
656                         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
657                                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
658                                 return true;
659                         end
660                 end
661
662                 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
663                 function event.update_option(name, field, allowed)
664                         local new = fields[field];
665                         if new == nil then return; end
666                         if allowed and not allowed[new] then return; end
667                         if new == self["get_"..name](self) then return; end
668                         event.status_codes["104"] = true;
669                         self["set_"..name](self, new);
670                         return true;
671                 end
672                 module:fire_event("muc-config-submitted", event);
673                 for submitted_field in pairs(present) do
674                         event.field, event.value = submitted_field, fields[submitted_field];
675                         module:fire_event("muc-config-submitted/"..submitted_field, event);
676                 end
677                 event.field, event.value = nil, nil;
678
679                 if self.save then self:save(true); end
680                 origin.send(st.reply(stanza));
681
682                 if next(event.status_codes) then
683                         local msg = st.message({type='groupchat', from=self.jid})
684                                 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
685                         for code in pairs(event.status_codes) do
686                                 msg:tag("status", {code = code;}):up();
687                         end
688                         msg:up();
689                         self:broadcast_message(msg);
690                 end
691         else
692                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
693         end
694         return true;
695 end
696
697 -- Removes everyone from the room
698 function room_mt:clear(x)
699         x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
700         local occupants_updated = {};
701         for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
702                 occupant.role = nil;
703                 self:save_occupant(occupant);
704                 occupants_updated[occupant] = true;
705         end
706         for occupant in pairs(occupants_updated) do
707                 self:publicise_occupant_status(occupant, x);
708                 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
709         end
710 end
711
712 function room_mt:destroy(newjid, reason, password)
713         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
714                 :tag("item", { affiliation='none', role='none' }):up()
715                 :tag("destroy", {jid=newjid});
716         if reason then x:tag("reason"):text(reason):up(); end
717         if password then x:tag("password"):text(password):up(); end
718         x:up();
719         self:clear(x);
720         module:fire_event("muc-room-destroyed", { room = self });
721 end
722
723 function room_mt:handle_disco_info_get_query(origin, stanza)
724         origin.send(self:get_disco_info(stanza));
725         return true;
726 end
727
728 function room_mt:handle_disco_items_get_query(origin, stanza)
729         origin.send(self:get_disco_items(stanza));
730         return true;
731 end
732
733 function room_mt:handle_admin_query_set_command(origin, stanza)
734         local item = stanza.tags[1].tags[1];
735         if not item then
736                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
737         end
738         if item.attr.jid then -- Validate provided JID
739                 item.attr.jid = jid_prep(item.attr.jid);
740                 if not item.attr.jid then
741                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
742                         return true;
743                 end
744         end
745         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
746                 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
747                 if occupant then item.attr.jid = occupant.jid; end
748         elseif not item.attr.nick and item.attr.jid then
749                 local nick = self:get_occupant_jid(item.attr.jid);
750                 if nick then item.attr.nick = select(3, jid_split(nick)); end
751         end
752         local actor = stanza.attr.from;
753         local reason = item:get_child_text("reason");
754         local success, errtype, err
755         if item.attr.affiliation and item.attr.jid and not item.attr.role then
756                 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
757         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
758                 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
759         else
760                 success, errtype, err = nil, "cancel", "bad-request";
761         end
762         if not success then
763                 origin.send(st.error_reply(stanza, errtype, err));
764         else
765                 origin.send(st.reply(stanza));
766         end
767         return true;
768 end
769
770 function room_mt:handle_admin_query_get_command(origin, stanza)
771         local actor = stanza.attr.from;
772         local affiliation = self:get_affiliation(actor);
773         local item = stanza.tags[1].tags[1];
774         local _aff = item.attr.affiliation;
775         local _aff_rank = valid_affiliations[_aff or "none"];
776         local _rol = item.attr.role;
777         if _aff and _aff_rank and not _rol then
778                 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
779                 -- e.g. an admin can't ask for a list of owners
780                 local affiliation_rank = valid_affiliations[affiliation or "none"];
781                 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
782                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
783                         for jid in self:each_affiliation(_aff or "none") do
784                                 reply:tag("item", {affiliation = _aff, jid = jid}):up();
785                         end
786                         origin.send(reply:up());
787                         return true;
788                 else
789                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
790                         return true;
791                 end
792         elseif _rol and valid_roles[_rol or "none"] and not _aff then
793                 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
794                 if valid_roles[role or "none"] >= valid_roles.moderator then
795                         if _rol == "none" then _rol = nil; end
796                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
797                         -- TODO: whois check here? (though fully anonymous rooms are not supported)
798                         for occupant_jid, occupant in self:each_occupant() do
799                                 if occupant.role == _rol then
800                                         local nick = select(3,jid_split(occupant_jid));
801                                         self:build_item_list(occupant, reply, false, nick);
802                                 end
803                         end
804                         origin.send(reply:up());
805                         return true;
806                 else
807                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
808                         return true;
809                 end
810         else
811                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
812                 return true;
813         end
814 end
815
816 function room_mt:handle_owner_query_get_to_room(origin, stanza)
817         if self:get_affiliation(stanza.attr.from) ~= "owner" then
818                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
819                 return true;
820         end
821
822         self:send_form(origin, stanza);
823         return true;
824 end
825 function room_mt:handle_owner_query_set_to_room(origin, stanza)
826         if self:get_affiliation(stanza.attr.from) ~= "owner" then
827                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
828                 return true;
829         end
830
831         local child = stanza.tags[1].tags[1];
832         if not child then
833                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
834                 return true;
835         elseif child.name == "destroy" then
836                 local newjid = child.attr.jid;
837                 local reason = child:get_child_text("reason");
838                 local password = child:get_child_text("password");
839                 self:destroy(newjid, reason, password);
840                 origin.send(st.reply(stanza));
841                 return true;
842         elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
843                 return self:process_form(origin, stanza);
844         else
845                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
846                 return true;
847         end
848 end
849
850 function room_mt:handle_groupchat_to_room(origin, stanza)
851         local from = stanza.attr.from;
852         local occupant = self:get_occupant_by_real_jid(from);
853         if module:fire_event("muc-occupant-groupchat", {
854                 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
855         }) then return true; end
856         stanza.attr.from = occupant.nick;
857         self:broadcast_message(stanza);
858         stanza.attr.from = from;
859         return true;
860 end
861
862 -- Role check
863 module:hook("muc-occupant-groupchat", function(event)
864         local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
865         if role_rank <= valid_roles.none then
866                 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
867                 return true;
868         elseif role_rank <= valid_roles.visitor then
869                 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
870                 return true;
871         end
872 end, 50);
873
874 -- hack - some buggy clients send presence updates to the room rather than their nick
875 function room_mt:handle_presence_to_room(origin, stanza)
876         local current_nick = self:get_occupant_jid(stanza.attr.from);
877         local handled
878         if current_nick then
879                 local to = stanza.attr.to;
880                 stanza.attr.to = current_nick;
881                 handled = self:handle_presence_to_occupant(origin, stanza);
882                 stanza.attr.to = to;
883         end
884         return handled;
885 end
886
887 -- Need visitor role or higher to invite
888 module:hook("muc-pre-invite", function(event)
889         local room, stanza = event.room, event.stanza;
890         local _from = stanza.attr.from;
891         local inviter = room:get_occupant_by_real_jid(_from);
892         local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
893         if valid_roles[role or "none"] <= valid_roles.visitor then
894                 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
895                 return true;
896         end
897 end);
898
899 function room_mt:handle_mediated_invite(origin, stanza)
900         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
901         local invitee = jid_prep(payload.attr.to);
902         if not invitee then
903                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
904                 return true;
905         elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
906                 return true;
907         end
908         local invite = muc_util.filter_muc_x(st.clone(stanza));
909         invite.attr.from = self.jid;
910         invite.attr.to = invitee;
911         invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
912                         :tag('invite', {from = stanza.attr.from;})
913                                 :tag('reason'):text(payload:get_child_text("reason")):up()
914                         :up()
915                 :up();
916         if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
917                 self:route_stanza(invite);
918         end
919         return true;
920 end
921
922 -- COMPAT: Some older clients expect this
923 module:hook("muc-invite", function(event)
924         local room, stanza = event.room, event.stanza;
925         local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
926         local reason = invite:get_child_text("reason");
927         stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
928                 :text(reason or "")
929         :up();
930 end);
931
932 -- Add a plain message for clients which don't support invites
933 module:hook("muc-invite", function(event)
934         local room, stanza = event.room, event.stanza;
935         if not stanza:get_child("body") then
936                 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
937                 local reason = invite:get_child_text("reason") or "";
938                 stanza:tag("body")
939                         :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
940                 :up();
941         end
942 end);
943
944 function room_mt:handle_mediated_decline(origin, stanza)
945         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
946         local declinee = jid_prep(payload.attr.to);
947         if not declinee then
948                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
949                 return true;
950         elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
951                 return true;
952         end
953         local decline = muc_util.filter_muc_x(st.clone(stanza));
954         decline.attr.from = self.jid;
955         decline.attr.to = declinee;
956         decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
957                         :tag("decline", {from = stanza.attr.from})
958                                 :tag("reason"):text(payload:get_child_text("reason")):up()
959                         :up()
960                 :up();
961         if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
962                 declinee = decline.attr.to; -- re-fetch, in case event modified it
963                 local occupant
964                 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
965                         occupant = self:get_occupant_by_nick(declinee);
966                 end
967                 if occupant then
968                         self:route_to_occupant(occupant, decline);
969                 else
970                         self:route_stanza(decline);
971                 end
972         end
973         return true;
974 end
975
976 -- Add a plain message for clients which don't support declines
977 module:hook("muc-decline", function(event)
978         local room, stanza = event.room, event.stanza;
979         if not stanza:get_child("body") then
980                 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
981                 local reason = decline:get_child_text("reason") or "";
982                 stanza:tag("body")
983                         :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
984                 :up();
985         end
986 end);
987
988 function room_mt:handle_message_to_room(origin, stanza)
989         local type = stanza.attr.type;
990         if type == "groupchat" then
991                 return self:handle_groupchat_to_room(origin, stanza)
992         elseif type == "error" and is_kickable_error(stanza) then
993                 return self:handle_kickable(origin, stanza)
994         elseif type == nil then
995                 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
996                 if x then
997                         local payload = x.tags[1];
998                         if payload == nil then --luacheck: ignore 542
999                                 -- fallthrough
1000                         elseif payload.name == "invite" and payload.attr.to then
1001                                 return self:handle_mediated_invite(origin, stanza)
1002                         elseif payload.name == "decline" and payload.attr.to then
1003                                 return self:handle_mediated_decline(origin, stanza)
1004                         end
1005                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1006                         return true;
1007                 end
1008         end
1009 end
1010
1011 function room_mt:route_stanza(stanza) -- luacheck: ignore 212
1012         module:send(stanza);
1013 end
1014
1015 function room_mt:get_affiliation(jid)
1016         local node, host, resource = jid_split(jid);
1017         local bare = node and node.."@"..host or host;
1018         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1019         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1020         return result;
1021 end
1022
1023 -- Iterates over jid, affiliation pairs
1024 function room_mt:each_affiliation(with_affiliation)
1025         if not with_affiliation then
1026                 return pairs(self._affiliations);
1027         else
1028                 return function(_affiliations, jid)
1029                         local affiliation;
1030                         repeat -- Iterate until we get a match
1031                                 jid, affiliation = next(_affiliations, jid);
1032                         until jid == nil or affiliation == with_affiliation
1033                         return jid, affiliation;
1034                 end, self._affiliations, nil
1035         end
1036 end
1037
1038 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1039         if not actor then return nil, "modify", "not-acceptable"; end;
1040
1041         local node, host, resource = jid_split(jid);
1042         if not host then return nil, "modify", "not-acceptable"; end
1043         jid = jid_join(node, host); -- Bare
1044         local is_host_only = node == nil;
1045
1046         if valid_affiliations[affiliation or "none"] == nil then
1047                 return nil, "modify", "not-acceptable";
1048         end
1049         affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1050
1051         local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1052         local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1053
1054         if actor == true then
1055                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1056         else
1057                 local actor_affiliation = self:get_affiliation(actor);
1058                 if actor_affiliation == "owner" then
1059                         if jid_bare(actor) == jid then -- self change
1060                                 -- need at least one owner
1061                                 local is_last = true;
1062                                 for j in self:each_affiliation("owner") do
1063                                         if j ~= jid then is_last = false; break; end
1064                                 end
1065                                 if is_last then
1066                                         return nil, "cancel", "conflict";
1067                                 end
1068                         end
1069                         -- owners can do anything else
1070                 elseif affiliation == "owner" or affiliation == "admin"
1071                         or actor_affiliation ~= "admin"
1072                         or target_affiliation == "owner" or target_affiliation == "admin" then
1073                         -- Can't demote owners or other admins
1074                         return nil, "cancel", "not-allowed";
1075                 end
1076         end
1077
1078         -- Set in 'database'
1079         self._affiliations[jid] = affiliation;
1080
1081         -- Update roles
1082         local role = self:get_default_role(affiliation);
1083         local role_rank = valid_roles[role or "none"];
1084         local occupants_updated = {}; -- Filled with old roles
1085         for nick, occupant in self:each_occupant() do -- luacheck: ignore 213
1086                 if occupant.bare_jid == jid or (
1087                         -- Outcast can be by host.
1088                         is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1089                 ) then
1090                         -- need to publcize in all cases; as affiliation in <item/> has changed.
1091                         occupants_updated[occupant] = occupant.role;
1092                         if occupant.role ~= role and (
1093                                 is_downgrade or
1094                                 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1095                         ) then
1096                                 occupant.role = role;
1097                                 self:save_occupant(occupant);
1098                         end
1099                 end
1100         end
1101
1102         -- Tell the room of the new occupant affiliations+roles
1103         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1104         if not role then -- getting kicked
1105                 if affiliation == "outcast" then
1106                         x:tag("status", {code="301"}):up(); -- banned
1107                 else
1108                         x:tag("status", {code="321"}):up(); -- affiliation change
1109                 end
1110         end
1111         local is_semi_anonymous = self:get_whois() == "moderators";
1112         for occupant, old_role in pairs(occupants_updated) do
1113                 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1114                 if occupant.role == nil then
1115                         module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1116                 elseif is_semi_anonymous and
1117                         (old_role == "moderator" and occupant.role ~= "moderator") or
1118                         (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1119                         -- Send everyone else's presences (as jid visibility has changed)
1120                         for real_jid in occupant:each_session() do
1121                                 self:send_occupant_list(real_jid, function(occupant_jid, occupant) --luacheck: ignore 212 433
1122                                         return occupant.bare_jid ~= jid;
1123                                 end);
1124                         end
1125                 end
1126         end
1127
1128         if self.save then self:save(); end
1129
1130         module:fire_event("muc-set-affiliation", {
1131                 room = self;
1132                 actor = actor;
1133                 jid = jid;
1134                 affiliation = affiliation or "none";
1135                 reason = reason;
1136                 previous_affiliation = target_affiliation;
1137                 in_room = next(occupants_updated) ~= nil;
1138         });
1139
1140         return true;
1141 end
1142
1143 function room_mt:get_role(nick)
1144         local occupant = self:get_occupant_by_nick(nick);
1145         return occupant and occupant.role or nil;
1146 end
1147
1148 function room_mt:set_role(actor, occupant_jid, role, reason)
1149         if not actor then return nil, "modify", "not-acceptable"; end
1150
1151         local occupant = self:get_occupant_by_nick(occupant_jid);
1152         if not occupant then return nil, "modify", "not-acceptable"; end
1153
1154         if valid_roles[role or "none"] == nil then
1155                 return nil, "modify", "not-acceptable";
1156         end
1157         role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1158
1159         if actor == true then
1160                 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1161         else
1162                 -- Can't do anything to other owners or admins
1163                 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1164                 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1165                         return nil, "cancel", "not-allowed";
1166                 end
1167
1168                 -- If you are trying to give or take moderator role you need to be an owner or admin
1169                 if occupant.role == "moderator" or role == "moderator" then
1170                         local actor_affiliation = self:get_affiliation(actor);
1171                         if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1172                                 return nil, "cancel", "not-allowed";
1173                         end
1174                 end
1175
1176                 -- Need to be in the room and a moderator
1177                 local actor_occupant = self:get_occupant_by_real_jid(actor);
1178                 if not actor_occupant or actor_occupant.role ~= "moderator" then
1179                         return nil, "cancel", "not-allowed";
1180                 end
1181         end
1182
1183         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1184         if not role then
1185                 x:tag("status", {code = "307"}):up();
1186         end
1187         occupant.role = role;
1188         self:save_occupant(occupant);
1189         self:publicise_occupant_status(occupant, x, nil, actor, reason);
1190         if role == nil then
1191                 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1192         end
1193         return true;
1194 end
1195
1196 local whois = module:require "muc/whois";
1197 room_mt.get_whois = whois.get;
1198 room_mt.set_whois = whois.set;
1199
1200 local _M = {}; -- module "muc"
1201
1202 function _M.new_room(jid, config) -- luacheck: ignore 212
1203         -- TODO use config?
1204         return setmetatable({
1205                 jid = jid;
1206                 _jid_nick = {};
1207                 _occupants = {};
1208                 _data = {
1209                 };
1210                 _affiliations = {};
1211         }, room_mt);
1212 end
1213
1214 _M.room_mt = room_mt;
1215
1216 return _M;