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