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