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