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