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